代码之家  ›  专栏  ›  技术社区  ›  notacorn

例如,如何将字符串形式的已解析Promise对象映射到按钮上

  •  1
  • notacorn  · 技术社区  · 7 年前

    我了解有很多类似的现有问题,但这些问题对于我的案例来说都不够简单。

    这是我现在承诺的行为:

    至少在第62行和第63行,我们可以通过控制台看到找到了准确和正确的值。我的目标是将其作为一个值传递给 somevar 或以其他方式用更新的值更新第70行。

    现在,我的按钮只需呈现 object[promise] and don't change after the promise has been resolved.

    这基本上是我写过的第一个Promise函数,老实说,我很迷茫,尽管其他人详细解释了我认为超出了我需要知道的范围,为API调用构造一个简单的Promise。

    完整代码:

    import react from'react';
    从“react instantsearch dom”导入highlight;
    从“@material ui/core/card”导入卡;
    从“@material ui/core/typography”导入版式;
    从“@material ui/core/paper”导入纸张;
    从“下一个/链接”导入链接;
    从“@material ui/styles”导入makestyles”;
    导入“.../static/default.css”;
    从“algoliasearch”导入algoliasearch;
    
    const searchclient=算法搜索(
    ****************
    ;
    
    const index=searchclient.initindex(“parks”);
    
    const useStyles=生成样式({
    根:{
    背景:'线性梯度(45度,4496db 30%,5df78e 90%)',
    边界:0,
    字体大小:16,
    边界半径:3,
    boxshadow:'0 3px 5px 2px rgba(255,105,135,.3)',
    颜色:“白色”,
    身高:48,
    宽度:“100%”,
    填充:“0 30px”,
    }
    卡:{
    最小宽度:275,
    }
    子弹:{
    display:'内联块',
    边距:“0 2px”,
    transform:'比例(0.8)',
    }
    题目:{
    字体大小:14,
    }
    POS:{
    边缘底部:12,
    }
    (});
    
    函数索引搜索(objid){
    返回新承诺((解决,拒绝)=>。{
    index.getobject(objid,['fullname'],(err,content)=>。{
    如果(内容)!{NULL){
    解析(content.fullname);
    }
    否则{
    拒绝(错误());
    }
    (});
    (});
    }
    
    函数NewButton(RedirectID){
    const classes=useStyles();
    var somevar=indexsearch(redirectid).then(函数(结果){
    console.log(结果);
    返回结果;
    }).catch(函数rejected()console.log('rejected'));
    console.log('在'+somevar之后);
    返回(
    <link as=`/details/$redirectid ` href=`/details?objectid=$重定向ID `>
    a & gt;
    <button type=“button”classname=classes.root>
    `了解更多关于$somevar `
    &按钮/按钮;
    & lt;/a & gt;
    L/Link & GT;
    )
    }
    
    类命中扩展react.component{
    
    RelDead(){
    const props=此.props;
    返回(
    
    卡& GT;
    <paper id=“paper”方形>
    <typography id=“title”color=“textprimary”variant=“h6”>
    <highlight classname=“ais highlight header”attribute=“fullname”hit=props.hit/>
    <highlight classname=“ais highlight state”attribute=“states”hit=props.hit/>
    </typography>
    &纸张& GT;
    <纸制方形>
    <typography color=“textsecondary”variant=“h6”>
    <highlight attribute=“description”hit=props.hit/>
    </typography>
    &纸张& GT;
    <newbutton redirectid=props.hit.objectid/>
    &卡/卡;
    )
    }
    }
    
    导出默认命中;
    < /代码> <从现在开始我的承诺:

    enter image description here

    至少在第62行和第63行,我们可以通过控制台看到找到了准确和正确的值。我的目标是要么把它作为一个值传递给someVar或者用更新后的值更新第70行。

    现在,我的按钮只是呈现Object [Promise]承诺达成后不要改变。

    这基本上是我写过的第一个Promise函数,尽管其他人给出了一些详细的解释,我认为这超出了构建API调用的简单Promise所需的知识,但我还是很不诚实。

    完整代码:

    import React from 'react';
    import {Highlight} from "react-instantsearch-dom";
    import Card from '@material-ui/core/Card';
    import Typography from '@material-ui/core/Typography';
    import Paper from '@material-ui/core/Paper';
    import Link from 'next/link';
    import {makeStyles} from "@material-ui/styles";
    import '../static/default.css';
    import algoliasearch from "algoliasearch";
    
    const searchClient = algoliasearch(
        **************************
    );
    
    const index = searchClient.initIndex("Parks");
    
    const useStyles = makeStyles({
        root: {
            background: 'linear-gradient(45deg, #4496DB 30%, #5df78e 90%)',
            border: 0,
            fontSize: 16,
            borderRadius: 3,
            boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
            color: 'white',
            height: 48,
            width: "100%",
            padding: '0 30px',
        },
        card: {
            minWidth: 275,
        },
        bullet: {
            display: 'inline-block',
            margin: '0 2px',
            transform: 'scale(0.8)',
        },
        title: {
            fontSize: 14,
        },
        pos: {
            marginBottom: 12,
        },
    });
    
    function indexSearch(objId){
        return new Promise((resolve, reject) => {
            index.getObject(objId, ['fullName'], (err, content) => {
                if (content != null){
                    resolve(content.fullName);
                }
                else{
                    reject(Error());
                }
            });
        });
    }
    
    function NewButton({redirectId}){
        const classes = useStyles();
        var someVar = indexSearch(redirectId).then(function(result){
            console.log(result);
            return result;
        }).catch(function rejected() {console.log('rejected')});
        console.log('after' + someVar);
        return(
            <Link as={`/details/${redirectId}`} href={`/details?objectId=${redirectId}`}>
                <a>
                    <button type="button" className={classes.root}>
                        {`Learn more about the ${someVar}`}
                    </button>
                </a>
            </Link>
        )
    }
    
    class Hit extends React.Component{
    
        render() {
            const props = this.props;
            return(
    
                <Card>
                    <Paper id="paper" square>
                        <Typography id="title" color="textPrimary" variant="h6">
                            <Highlight className="ais-Highlight-header" attribute="fullName" hit={props.hit}/>
                            <Highlight className="ais-Highlight-state" attribute="states" hit={props.hit}/>
                        </Typography>
                    </Paper>
                    <Paper square>
                        <Typography color="textSecondary" variant="h6">
                            <Highlight attribute="description" hit={props.hit}/>
                        </Typography>
                    </Paper>
                    <NewButton redirectId={props.hit.objectID}/>
                </Card>
            )
        }
    }
    
    export default Hit;
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Nicholas Tower    7 年前

    function NewButton({redirectId}){
      const classes = useStyles();
      const [someVar, setSomeVar] = useState(null);
    
      useEffect(() => {
        indexSearch(redirectId).then(result => {
          setSomeVar(result);
        }) 
      }, [])
    
      if (!someVar) {
        return null;
      }
    
      return(
          <Link as={`/details/${redirectId}`} href={`/details?objectId=${redirectId}`}>
              <a>
                  <button type="button" className={classes.root}>
                      {`Learn more about the ${someVar}`}
                  </button>
              </a>
          </Link>
      )
    }