javascript - 如何保存子组件的数据和状态?

标签 javascript reactjs react-native

这是我的代码:

var Component_1 = React.createClass({
        getInitialState: function() {
            return {
                subcomponents: []
            };
        },
        componentWillReceiveProps: function(nextProps) {
            //push new subcomponent into 'subcomponents'
            this.state.subcomponents.push(nextProps.ele);
        },
        render: function() {
            return (
                <div>
                    {this.state.subcomponents}
                </div>
            );
        }
    });

    // A router like that:
    var hash = window.location.hash
    if (hash === '#way1') {
        React.render( < Component ele={<SubComponent_1 />} /> , document.body);
    } else if (hash === '#way2') {
        React.render( < Component ele={<SubComponent_2 />} /> , document.body);
    } else {
        React.render( < Component ele={<SubComponent_3 />} /> , document.body);
    }

代码很简单:当位置哈希更改时,重新渲染 <Component />带有新 Prop ele (ele 的值是一个子组件)。

每次重新渲染 Component将触发componentWillReceiveProps并推<Subcomponent_* />进入subcomponents .

因此在特定情况下,<Component />可能看起来像这样:

<div>
    <SubComponent_1 />
    <SubComponent_2 />
</div>

我的目的是:如何将整个数据(例如用户在 input 元素中输入的某些数据)保留在 <SubComponent_1 /> 中,当 <SubComponent_2 />插入subcomponents并触发<Component />使用两个子组件重新渲染?

更新:

何时 <SubComponent_1 />以某种方式被删除,如何保留 <SubComponent_2 /> 的全部数据?我发现添加key所有子组件的 prop 都不起作用。

最佳答案

看起来您会想要使用react-router通过某种通量实现。

路由器将处理所有#更改和flux将保持您的应用程序状态。

Redux作为通量实现变得非常流行。

有大量资源可以将这些东西组合在一起:

对于您的用例,我建议以下路由器配置:

<Router>
  <Route path='/' component={Component}>
    <Route path='way1' component={SubComponent_1} />
    <Route path='way2' component={SubComponent_2} />
    <IndexRoute component={SubComponent_3} />
  </Route>
</Router>

然后在您的 Component 渲染函数中,您只需要包含

{this.props.children} 

关于javascript - 如何保存子组件的数据和状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32839159/

相关文章:

javascript - 是否可以监听另一个组件的卸载生命周期

reactjs - React Native - 在按钮 onPress 中访问 'this' 导致应用程序崩溃

javascript - 如何使用 React Native 从 api 加载数据

javascript - jQuery:在悬停在附近的元素上时更改不透明度

javascript - 成功时拒绝 $http promise

javascript - 我在改变 reducer 中的 redux 状态吗?

javascript - 自动对焦不适用于 React Native Formik

javascript - 如何在 Semantic-UI-React 下拉菜单中选择图像?

javascript - 如何使用 CSS 或 Javascript 创建选取框

javascript - React - 将计算样式传递给 div 的语法