0
我有一个部件如何在Reactjs中切换组件时保持状态?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {stories: []};
}
componentDidMount() {
$.get(Api.getList(), (result) => {
const data = result;
if (data) {
this.setState((prevState) => ({
stories: data.stories
}));
}
});
}
render() {
if(this.state.stories.length==0){
return (
<Tpl>
<Loading/>
</Tpl>
);
}else{
return (
<Tpl>
<Stories stories={this.state.stories} />
</Tpl>
);
}
}
}
,每次当我切换到该组件, 它将运行constructor
第一。 所以国家将是空的。
我想要的是如果stories
有项目,它不需要再次获取数据。
是否有任何方法来保持这种状态?