我实际上正在学习reactjs,而我实际上正在开发一个包含在名为TODO的“父组件”内的小TODO列表。Reactjs,父组件,状态和道具
在这个父类的内部,我想从关注的存储中获取TODO的当前状态,然后将此状态作为属性传递给子组件。
问题是,我不知道在哪里初始化我的父状态值。其实,我使用ES6语法,所以我没有getInitialState()函数。它写在文档中,我应该使用组件构造函数来初始化这些状态值。
事实是,如果我想初始化我的构造函数内部的状态,this.context(Fluxible Context)实际上是未定义的。
我决定移动componentDidMount中的初始化,但它似乎是反模式,我需要另一种解决方案。你可以帮我吗 ?
这里是我的实际代码:
import React from 'react';
import TodoTable from './TodoTable';
import ListStore from '../stores/ListStore';
class Todo extends React.Component {
constructor(props){
super(props);
this.state = {listItem:[]};
this._onStoreChange = this._onStoreChange.bind(this);
}
static contextTypes = {
executeAction: React.PropTypes.func.isRequired,
getStore: React.PropTypes.func.isRequired
};
componentDidMount() {
this.setState(this.getStoreState()); // this is what I need to move inside of the constructor
this.context.getStore(ListStore).addChangeListener(this._onStoreChange);
}
componentWillUnmount() {
this.context.getStore(ListStore).removeChangeListener(this._onStoreChange);
}
_onStoreChange() {
this.setState(this.getStoreState());
}
getStoreState() {
return {
listItem: this.context.getStore(ListStore).getItems() // gives undefined
}
}
add(e){
this.context.executeAction(function (actionContext, payload, done) {
actionContext.dispatch('ADD_ITEM', {name:'toto', key:new Date().getTime()});
});
}
render() {
return (
<div>
<button className='waves-effect waves-light btn' onClick={this.add.bind(this)}>Add</button>
<TodoTable listItems={this.state.listItem}></TodoTable>
</div>
);
}
}
export default Todo;
我很好奇,你在哪里读到,在componentDidMount方法中获取或设置'state'是一个_anti-pattern_? –
@TahirAhmed,在这里:https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html –
hmm但它在那篇文章中提到了'componentDidMount'?我的意思是我在我的项目中所做的几乎与你正在做的一样,即在'componentDidMount'函数内使用'this.setState(...)',直到现在,我认为使用它就好了。我现在很好奇别人怎么看,因为我个人认为没有任何问题。 –