![](/img/trans.png)
[英]How can i initialize state by passing props from parent component to child component in ReactJS?
[英]Reactjs, parent component, state and props
我實際上是在學習reactjs,實際上是在開發一個小的TODO列表,該列表包裝在稱為“ TODO”的“父組件”中。
在此父級內部,我想從相關商店獲取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;
作為Fluxible用戶,您應該從Fluxible插件中受益:
下面的示例將監聽FooStore和BarStore中的更改,並在實例化組件時將foo和bar作為prop傳遞給Component。
class Component extends React.Component {
render() {
return (
<ul>
<li>{this.props.foo}</li>
<li>{this.props.bar}</li>
</ul>
);
}
}
Component = connectToStores(Component, [FooStore, BarStore], (context, props) => ({
foo: context.getStore(FooStore).getFoo(),
bar: context.getStore(BarStore).getBar()
}));
export default Component;
查看可變動的示例以獲取更多詳細信息。 代碼摘錄:
var connectToStores = require('fluxible-addons-react/connectToStores');
var TodoStore = require('../stores/TodoStore');
...
TodoApp = connectToStores(TodoApp, [TodoStore], function (context, props) {
return {
items: context.getStore(TodoStore).getAll()
};
});
因此,您無需調用setState,所有存儲數據都將在組件的props中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.