Javascript 变异然后重新加载组件

Javascript 变异然后重新加载组件,javascript,reactjs,Javascript,Reactjs,我有一个组件,带有一个“like”图标的事件处理程序。我希望能够单击like图标,更新数据库以记录用户喜欢该项目,然后重新渲染组件以更改图标以反映用户喜欢该项目。这是行不通的。似乎重序发生在突变之前,所以我无法识别这些变化。代码如下: handleFavourite = () => { const { post, client: apolloClient, currUser, registerPromise } = this

我有一个组件,带有一个“like”图标的事件处理程序。我希望能够单击like图标,更新数据库以记录用户喜欢该项目,然后重新渲染组件以更改图标以反映用户喜欢该项目。这是行不通的。似乎重序发生在突变之前,所以我无法识别这些变化。代码如下:

handleFavourite = () => {
    const {
      post, 
      client: apolloClient,
      currUser,
      registerPromise
    } = this.props;
    var result;
    const postId = post._id;
    if (currUser.library.includes(post._id)) {
      console.log("changed to not liked")        
      result = removeFromLibrary({postId: postId}  , apolloClient);
    }else {
      console.log("changed to yes, liked!")
      result = addToLibrary( {postId: postId} , apolloClient);
    };
    this.setState(state => ({ liked: !currUser.library.includes(post._id) }));

    return result;
以下是渲染中用于将图标设置为适当状态的代码:

<CardActions className={classes.actions} disableActionSpacing>
  <IconButton
    className={classnames(classes.unliked, {
      [classes.liked]: currUser.library.includes(post._id),
    })}
    aria-label="Add to favorites"
    onClick={this.handleFavourite}
  >
    <FavoriteIcon />

假设removeFromLibrary和addToLibrary是异步函数,您可以等待完成

handleFavourite = async () => {
    const {
      post, 
      client: apolloClient,
      currUser,
      registerPromise
    } = this.props;
    var result;
    const postId = post._id;
    if (currUser.library.includes(post._id)) {
      console.log("changed to not liked")        
      result = await removeFromLibrary({postId: postId}  , apolloClient);
    }else {
      console.log("changed to yes, liked!")
      result = await addToLibrary( {postId: postId} , apolloClient);
    };
    this.setState(state => ({ liked: !currUser.library.includes(post._id) }));

    return result;

您的
removeFromLibrary
addToLibrar
async?回调是的,它们是异步的。我现在正在研究这一点,看到这将影响事情的顺序。我还是很困惑。玄鸿哲的回答应该能解决你的问题!此外,您可能不必返回结果,因为它之后不会在任何地方使用