繁体   English   中英

React.js,父组件,状态和道具

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM