繁体   English   中英

Redux,反应。 如何将mapStateToProps添加到this.state?

[英]Redux, react. How I can add mapStateToProps into this.state?

我有操作和中间件,可以在其中进行提取请求。 我在mapStateToProps中获得了数据。

但是我想在我的状态下使用此数据并在setState中更改它们。 如何将mapStateToProps添加到this.state?

我想在客户端过滤我的数据。 如果我将动作调度到服务器,则不必这样做,因为商店中有所有列表。

您可以通过在Redux存储更新(例如,分派的获取成功操作)并且组件接收新值后更新组件的状态来实现此目的。

但是,这在大多数情况下不是惯用的,因为现在您必须处理本地组件状态和外部Redux状态的可能不同步(可以从组件外部进行更新,并且这些新值将传递给我们的组件)。
当然,您可以忽略这些更改,而对道具更改不做任何事情。
或反向-每次新道具到达时更新组件的状态。

这是同步道具和状态的示例:

// get `value` from store and pass it as prop to our component
const mapStateToProps = state => ({ value: state.someKey.value })

class Component extends React.Component {
  // new props has been passed
  // this method receives new props and current state
  // returns next state values, or null if no changes required
  static getDerivedStateFromProps(props, state) {
    // some complex comparison logic goes here
    // if true, then desync happened, let's update local state
    if (state.value !== props.value) {
      // this value will be at `this.state.value`
      return { value }
    }

    // else, no update needed for our state
    return null
  }

  // initial values taken from props
  state = { value: this.props.value }

  // update local state
  onChange = e => this.setState({ value: e.target.value })

  // let's render props value as label and state values as input value
  render() {
    return (
      <label>
        Props value is {this.props.value}
        <input value={this.state.value} onChange={this.onChange} />
      </label>
    )
  }
}

请注意, getDerivedStateFromProps是一个相对较新的生命周期方法(类似于“旧的” componentWillReceiveProps ),并且在官方文档中提到此用例可能是不良设计的标志。

TL; DR复制状态不好,尤其是如果我们必须手动同步它时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM