【问题标题】:Why is my if statement always giving the same result in React?为什么我的 if 语句在 React 中总是给出相同的结果?
【发布时间】:2020-12-14 22:02:47
【问题描述】:

我有一个按钮,可以将排序状态更改为真或假。这是使用回调从子级传递给 App 组件的。在单击按钮时,refinedApiRequest 中的第一个控制台日志给出的值是 true,然后是 false,然后是 true,依此类推。但是,无论排序状态如何(真或假),if 语句都会导致 else 结果。这是什么原因造成的?

我想根据排序状态为变量分配一个值,以便我可以将此值输入到异步 api 获取请求的参数中。提前致谢。

class App extends React.Component {
  state = { pictures: '', sort: '' };


  onSortSelect = sort => {
    this.setState({ sort: sort }, () => this.refinedApiRequest(sort));
  }

  async refinedApiRequest(sort) {

    console.log(sort);

    if(sort == 'true') {
      console.log('its true');
    } else {
      console.log('its false');
    }

    const res = await axios.get('url', {
      params: {
        order: {a variable}
      }
    });

    this.setState({ pictures: res.data });

    console.log(this.state.pictures);
  }

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    虽然保证this.setState 的可选callback 参数仅在重新渲染组件时执行,但在您的情况下,它仍然关闭前一个的sort 值渲染(参考:How do JavaScript closures work?)。

    我建议以下反应建议:

    setState() 的第二个参数是一个可选的回调函数,一旦 setState 完成并重新渲染组件,就会执行该回调函数。 一般我们建议使用 componentDidUpdate() 来代替此类逻辑。

    来自:https://reactjs.org/docs/react-component.html#setstate

    (我强调)

    【讨论】:

    • 感谢您的回复。 componentDidUpdate() 会在 onSortSelect 运行(并调用 setState)之后运行,而无需我将其作为回调传递吗?
    • @BoJack 查看文档reactjs.org/docs/react-component.html#componentdidupdate,了解如何使用它以及比我在此处复制的更好的解释。 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2012-11-14
    • 1970-01-01
    • 2017-09-21
    • 2012-12-20
    • 2015-12-07
    • 1970-01-01
    相关资源
    最近更新 更多