【问题标题】:setState after async action in redux [duplicate]在redux中异步操作后的setState [重复]
【发布时间】:2018-01-21 16:28:56
【问题描述】:

我应该使用哪种生命周期方法来设置表单中的现有值?我不能<input value={this.props.title} />,因为我想将输入作为受控组件。

我可以在异步方法之后做一个承诺,但这会是反模式吗?

componentDidMount() {
  this.props.fetchItem(this.itemId)
  .then(v=>{this.setState({title: v.title})})
}

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    您可以使用 componentWillReceiveProps() 方法将您的道具值设置为状态。

    类似的东西。

    componentWillReceiveProps(nextProps){
     // store your props value to state here
    if(nextProps.formData !== undefined){
      this.setState({ formData: nextProps.formData });
      }
    
    }
    

    在输入更改方法上更新该状态值

    handleChange = (name, value) => {
      // update state here
      this.setState({ [name]: value });
      }
    

    【讨论】:

    • nextProps.formData 最初是未定义的。
    • 您可以添加一些验证,例如 (nextProps.formData !== undefined)
    猜你喜欢
    • 2016-06-02
    • 2017-03-04
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 2017-06-23
    • 2017-09-26
    相关资源
    最近更新 更多