将状态更新直接推送到有条件渲染的React组件?

时间:2017-08-04 17:43:44

标签: javascript reactjs

我正在构建一个React应用并有一个标签部分,点击一个标签就会呈现一个特定的组件。

首先,我的父组件:



class Interface extends Component {
    constructor(props) {
        super(props);
        this.chooseTab = this.chooseTab.bind(this);
        this.state = {
            current: 'inventory',
            inventory: [],
            skills: [],
            friends: [],
            notifications: {}
        };
    }

    chooseTab(tabID) {
      this.setState({ current: tabID });

    chooseComponent(tabID) {
        if (tabID === 'skills') return Skills;
        else if (tabID === 'inventory') return Inventory;
        else if (tabID === 'friends') return FriendsList;
    }

    render() {
        const tabID = this.state.current;
        const CustomComponent = this.chooseComponent(tabID);
        return (
            <div className='column' id='interface'>
              <div className='row' id='tabs'>
                <ActiveTab
                  current={this.state.current}
                  tabID='skills'
                  chooseTab={this.chooseTab}
                />
                <ActiveTab
                  current={this.state.current}
                  tabID='inventory'
                  chooseTab={this.chooseTab}
                />
                <ActiveTab
                  current={this.state.current}
                  tabID='friends'
                  chooseTab={this.chooseTab}
                />
              </div>
              <TabBody>
                <CustomComponent
                  data={this.state[tabID]}
                  notifications={this.state.notifications}
                />
              </TabBody>
            </div>
        );
    }
}
&#13;
&#13;
&#13;

其中有三个ActiveTab和一个TabBody:

&#13;
&#13;
const ActiveTab = (props) => {
    const isActive = props.tabID === props.current ? 'active' : 'inactive';
    return (
      <button
        className={`active-tab ${isActive}`}
        onClick={() => props.chooseTab(props.tabID)}
      >{props.tabID}
      </button>
    );
};

const TabBody = (props) => {
    return (
        <div className='tab-body'>
          {props.children}
        </div>
    );
};
&#13;
&#13;
&#13;

这很好用,显然是处理此问题的intended way。不过,我希望能够将notifications州对象移动到我的FriendsList组件中(因为它对朋友来说是独一无二的)并且还会触发setState它来自另一个组件,即使FriendsList不是TabBody当前呈现的组件(即,未安装)。

我目前正在使用全局可用的actions闭包来触发远程状态更改,其中在目标元素的setState生命周期方法中定义了特定操作和ComponentWillMount(),并且它是从激活远程状态变化的任何组件执行的。为了简洁起见,我将Interface中的内容留下了。

你会怎么处理这个?我唯一的选择是将notifications留在Interface中,在那里定义操作,让React处理传递道具?或者有没有办法构建我的选项卡组件和条件渲染,以便我可以触发状态更改从单独的组件到其中一个选项卡中的非显示组件,即将notifications及其相应的操作移动到{{1 }}?

1 个答案:

答案 0 :(得分:1)

我几周前遇到了类似于你的问题,如果你没有决定采用像Redux,MobX甚至Flux这样的州长,我认为你应该把道具传给他们的孩子。