2017-02-16 53 views
0

我是新来reactjs框架和我有一点困惑,如果是什么在听取正确的方式,如果一个API调用后状态改变。收听时通过Redux的状态变化 - ReactJS

使用thencatch调用一个action经由componentDidUpdate后:

componentDidMount(){ 
     this.props.getHero(this.props.params.id).then((result) => { 
      this.props.initialize({ 
       "name":result.name, 
       "description": result.description 
      }); 
     }) 
     .catch(error => { 

     }); 
    } 

或经由componentWillUpdate

// Call the getHero action (API) 
componentDidMount(){ 
    this.props.getHero(this.props.params.id); 
} 

// Then listen if the state change via `mapToStateProps` 
componentDidMount(){ 
    this.props.getHero(this.props.params.id); 
} 
componentWillUpdate(){ 
     this.props.initialize({ 
      "name":this.props.heroes.name, 
      "description": this.props.heroes.description 
     }); 
    } 
+0

这是什么都与终极版呢? – Pavlo

+0

@Pavlo与componentWillUpdate第二块,我从我的行动派遣一个数据我通过API获取的数据经过这么componentWillUpdate将触发因为道具通过mapStateToProps改变。这就是为什么我问是否正确?我可以问你的建议吗? –

回答

2

侦听变化componentWillUpdate

componentWillUpdate()是调用d紧接在呈现新的道具或状态时收到。 使用此作为更新发生之前执行准备的机会。此方法不用于初始渲染。一个部件被安装在后componentDidMount

componentDidMount()

负载数据立即被调用。需要DOM节点的初始化应该放在这里。 如果您需要从远程端点加载数据,这是一个很好的地方来实例化网络请求。在此方法中设置状态将触发重新渲染。

+0

你可以有终极版 – juancab

+0

@juancab感谢创作者对这个[示例]看看(https://github.com/reactjs/redux/blob/master/examples/async/src/containers/App.js)! – lustoykov