【问题标题】:State is not updating in componentWillMountcomponentWillMount 中的状态未更新
【发布时间】:2016-10-21 13:59:54
【问题描述】:

当我尝试从 componentwillmount 函数中的 api 调用更新反应组件的状态时,它没有按预期工作。该值未设置。

export default class ListOfProducts extends Component {
        componentWillMount() {
            console.log('component currently mounting');
            fetchOrder().then(data => {
                console.log('order api call has been finished.', data);
                this.setState(data, function() {
       //this should print new data but i am still getting old data 
                    console.log('current this.state.', this.state.orders)
                })
            })
        }
        constructor(props) {
            super(props);

            this.state = {
                "orders": {
                    "order_items": []
                }
            };
        }
        render() {
            let productList = [];
            let productUnit = (
                <View>
          {this.state.orders.order_items.map(function(order,i){
            return <ProductListItem
              delivered={true}
              productSKU={3}/>
          })}
          </View>
            );
            return productUnit;
        }
    }

【问题讨论】:

  • 我不确定,但我认为您可以直接在 componentWillMount 中修改状态,因为组件尚未呈现,调用 setState 或调用 setState 是 componentDidMount 没有意义跨度>
  • 即使 this.state= 数据不工作
  • @RakeshYadav 您不应手动将任何值设置为this.state,因为当您调用setState() 时它们将被覆盖。
  • @Barry127 你可以直接在componentWillMount中更新状态。看到这个:componentWillMount() 是我们处理配置、更新状态以及为第一次渲染做准备的机会。至此,props 和初始状态就定义好了。我们可以安全地查询 this.props 和 this.state,确定它们是当前值。来自:here

标签: reactjs react-native


【解决方案1】:

如果你想执行任何异步请求,我建议你在componentDidMount生命周期方法中执行它们。这是基于Reactjs documentation for componentDidMount 的建议路径。

调用一次,仅在客户端(不在服务器上),立即 在初始渲染发生之后。在生命周期的这一点上, 您可以访问您孩子的任何参考资料(例如,访问 底层 DOM 表示)。 componentDidMount() 方法 子组件在父组件之前被调用。

如果您想与其他 JavaScript 框架集成,请设置计时器 使用 setTimeout 或 setInterval,或发送 AJAX 请求,执行那些 此方法中的操作。

【讨论】:

    【解决方案2】:

    也许你需要改变: “扩展组件{” 到 " 扩展 React.Component { "

    【讨论】:

    • 您好,欢迎来到 StackOverflow。当您发布答案时,请确信它会解决问题。如果您不确定并且仍然想发布您的想法,请尝试描述您认为它可以解决问题的原因。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2017-04-24
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 2015-06-11
    • 2017-05-20
    • 1970-01-01
    相关资源
    最近更新 更多