javascript - Redux 或 setTimeout - 如何观察子组件中的 props 变化?

标签 javascript reactjs redux settimeout

我有App组件,它从服务器加载JSON数据。 加载数据后,我更新子组件的状态。

现在我的函数如下所示:

componentDidMount() {
  setTimeout(()=> {
    if (this.state.users.length !== this.props.users.length) {
      this.setState({users: this.props.users});
      this.setState({tasks: this.getTasksArray()});
  }, 500);
}

我使用 setTimeout 来等待数据是否加载并发送给子进程。但我确信这不是最好的方法 也许,最好使用 redux 而不是 setTimeout。

父组件加载数据:

componentWillMount() {
  var _url = "/api/getusers/";
  fetch(_url)
  .then((response) => response.json())
  .then(users => {
    this.setState({ users });
    console.log("Loaded data:", users);
  });
}

父级发送 Prop :

<AllTasks users={this.state.users} />

所以,我的问题是:观察子组件变化的最佳方法是什么? 我的意思是在这种特殊情况下。

最佳答案

是的,这不是正确的方法,因为 api 调用将是异步的,我们不知道需要多长时间。

因此,不要使用 setTimeout,而是在子组件中使用 componentWillReceiveProps 生命周期方法,只要您更改 props 值(状态),它就会被调用父组件)。

像这样:

componentWillReceiveProps(newProps){
    this.setState({
        users: newProps.users,
        tasks: this.getTasksArray()
    })
}

还有一件事,不要在函数内多次调用 setState,因为 setState 会触发重新渲染,因此首先执行所有计算,然后执行 setState 在最后一次调用中更新所有值。

根据 DOC :

componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

更新:

您正在从 cWRP 方法调用一个方法,并使用该方法内的 props 值,this.props 将在之后获得更新的值仅此生命周期方法。因此,您需要将 newProps 值作为此函数中的参数传递,并使用它而不是this.props

像这样:

componentWillReceiveProps(newProps){
    this.setState({
        users: newProps.users,
        tasks: this.getTasksArray(newProps)
    })
}

getTasksArray(newProps){
    //here use newProps instead of this.props
}

查看此答案以了解更多详细信息:componentWillRecieveProps method is not working properly: ReactJS

关于javascript - Redux 或 setTimeout - 如何观察子组件中的 props 变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44811220/

相关文章:

javascript - 使用 prisma,如何从嵌套写入中访问新创建的记录(先更新,然后在其中创建)

reactjs - 如何在 typescript 中使用 react-navigation 的 withNavigation?

redux - 如何在 React Redux 应用程序中深度卡住 Redux 状态?

reactjs - 隐藏生产中的状态结构

javascript - 如何在给定代码的 JavaScript 对象中有条件地添加键

javascript - 没有函数文本的函数的 javascript 语法名称或术语?

javascript - 使用json数据在chart.js中绘制折线图

reactjs - React Hook "useCategory"无法在回调内调用

ios - 使用旧版本的 React Native 的新 React Native 项目

javascript - Redux 表单不允许编辑初始化表单状态值