gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:52:26 25 4
gpt4 key购买 nike

这是我的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com