Reactjs,父组件,状态和道具

时间:2015-09-06 12:35:12

标签: javascript reactjs reactjs-flux fluxible

我实际上正在学习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;

1 个答案:

答案 0 :(得分:1)

作为Fluxible用户,您应该受益于Fluxible addons

以下示例将侦听FooStore和BarStore中的更改,并在实例化时将foo和bar作为props传递给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;

查看fluxible example了解更多详情。代码exсerpt:

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,所有商店数据都将在组件的道具中。

相关问题