setInterval与React + Redux中的更新数据

问题描述

我的setInterval设置可以在componentDidMount中正常工作,但是参数没有更新。例如,text参数与最初安装组件时的值相同,尽管用户界面已更改。我确认text的值已在Redux存储中正确更新,但未传递给this.retrieveData(text)。我怀疑const { text } = this.props在componentDidMount中设置了值,尽管它有所不同,但禁止其更新。我将如何处理这个问题?

下面的代码一个示例,但我的实际用例是根据搜索条件检索数据。一旦用户更改了这些条件,它将以新结果进行更新。但是,我无法将这些新条件传递到componentDidMount中,因此页面每隔几秒钟会自动刷新。

class App extends React.Component {
   componentDidMount() {
      const { text } = this.props       //Redux store prop
      setInterval(() => this.retrieveData(text),3000)
   }

   retrieveData = (text) => {
      let res = axios.post('/search',{ text })
      updateResults(res.data)           //Redux action
   }

   render() {
      const { text,results } = this.props
      
      return (
          <input text onChange={(e) => updateText(e.target.value)} />
          <div>
              {results.map((item) => <p>{item}</p>}
          </div>
      )
   }
}

解决方法

由于您使用的是componentDidMountsetTimeout方法,因此retrieveData仅以文本的初始值被调用一次。如果您希望以当前的方式进行操作,请使用componentDidUpdate方法,每次更改道具或状态时都会调用该方法。您可以在https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/上找到有关生命周期的更多信息。

如果您要像在问题中一样使用setInterval,则只需在retrieveData方法内部访问props即可,而不是使用参数。

retrieveData = () => {
    let res = post("/search",{ text: this.props.text });
    updateResults(res); //Redux action
  };

您可以在https://codesandbox.io/s/charming-blackburn-khiim?file=/src/index.js

上找到这两种情况的工作示例

异步调用的最佳解决方案是使用https://github.com/reduxjs/redux-thunkhttps://redux-saga.js.org/之类的中间件。

您对input的看法也很小,应该是:

<input type="text" value={text} onChange={(e) => updateText(e.target.value)} />