Reactjs 为什么要重置设置状态?

Reactjs 为什么要重置设置状态?,reactjs,state,Reactjs,State,我在一个社区网站上工作,用户可以在网站上分享和评论(这里是)[网站可以按类别进行过滤,但当用户进入特定页面后退出时,过滤器将被删除 以下是分步骤的流程: 用户从下拉列表中选择过滤器,this.state.topicSelected反映新值 用户单击链接以查看实例(网站摘要)的显示页面,this.state.topicSelected反映了正确的值 用户返回主页,this.state.topicSelected将恢复为0 我希望该值仍然适用,而不是恢复为0,以便筛选器保留在用户以前选择的同一类

我在一个社区网站上工作,用户可以在网站上分享和评论(这里是)[网站可以按类别进行过滤,但当用户进入特定页面后退出时,过滤器将被删除

以下是分步骤的流程:

  • 用户从下拉列表中选择过滤器,
    this.state.topicSelected
    反映新值
  • 用户单击链接以查看实例(网站摘要)的显示页面,
    this.state.topicSelected
    反映了正确的值
  • 用户返回主页,
    this.state.topicSelected
    将恢复为
    0
我希望该值仍然适用,而不是恢复为0,以便筛选器保留在用户以前选择的同一类别上

问题似乎是
getInitialState
正在将
this.state.topicSelected
的值重置回
0
(正如它在代码中所写的那样)。当我尝试将动态值置于
0
位置时,我得到一个未定义的错误

下面是
getInitialState
代码:

        var SitesArea = React.createClass({
            getInitialState: function () {
                return {
                    sortSelected: "most-recent",
                    topicSelected: 0 // need to overwrite with value of this.state.topicSelected when user selects filter
// I removed other attributes to clean it up for your sake
                }
            }
以下是事件:

            onTopicClick: function (e) {
                e.preventDefault();
                this.setState({topicSelected: Number(e.target.value)});
                if (Number(e.target.value) == 0) {
                    if (this.state.sortSelected == 'highest-score') {
                        this.setState({sites: []}, function () {
                            this.setState({sites: this.state.score});
                        });
                    } else if (this.state.sortSelected == 'most-remarked') {
                        this.setState({sites: []}, function () {
                            this.setState({sites: this.state.remarkable});
                        });
                    } else if (this.state.sortSelected == 'most-visited') {
                        this.setState({sites: []}, function () {
                            this.setState({sites: this.state.visited});
                        });
                    } else if (this.state.sortSelected == 'most-recent') {
                        this.setState({sites: []}, function () {
                            this.setState({sites: this.state.recent});
                        });
                    }
                } else {
                    this.getSites(this.state.sortSelected, Number(e.target.value));
                    this.setState({sites: []}, function () {
                        this.setState({sites: this.state.filter_sites});
                    });
                }
最后是下拉菜单:

<select
  value={this.state.topicSelected}
  onChange={this.onTopicClick}
  className="sort"
  data-element>
    {
// Add this option in the .then() when populating siteCategories()
 [<option key='0'value='0'>Topics</option>].concat(
this.state.topics.map(function (topic) {
       return (<option
       key={topic.id}
       value={topic.id}>{topic.name}</option>);
  }))
}

{
//填充siteCategories()时,在.then()中添加此选项
[主题].concat(
this.state.topics.map(函数(主题){
返回({topic.name});
}))
}

如何获取它,以便当用户返回主页时,
this.state.topicSelected
不会重置?

我认为您的主页正在卸载(销毁)当用户从主页导航到摘要页面时。React在返回时创建主页组件的全新实例。该重构将所选主题初始化回0

这显示了可能发生的情况。
Foo
==您的主页,
Bar
==摘要页面。单击几次增量主题,然后从
Foo
导航到
Bar
,然后再返回。控制台日志显示
Foo
组件在导航离开时卸载,并在返回时重新构建

注意您似乎正在使用旧版本的react,这可以从存在
getInitialState
react.createClass
中看出。我的笔遵循了在类构造函数中初始化状态的更现代的方法

要解决这个问题,您必须将该状态保存在主组件之外的某个组件中,该组件在导航时不会被删除和重新创建

  • 从主页中公开一个
    onTopicSelected
    事件。主页的父级将传递一个函数处理程序作为挂钩该事件的道具。处理程序应将所选主题保存在父级的组件状态。这是一种混乱的解决方案,因为父级通常不应该知道或关心内部状态它的孩子
  • 将所选主题塞入一些没有反应的内容,如
    window.props
    。这也是一个丑陋的想法
  • 了解redux并将其插入应用程序
Redux是存储这种状态的最干净的方法,但它需要一些学习。如果您想了解它的外观,我已经在中实现了第一个解决方案

显示问题的原始代码笔作为代码段粘贴在下面。如果尝试在此处运行,请切换到完整页面模式

//jshint esnext:true
常数头=(道具)=>{
const{selectedPage,onNavigationChange}=props;
const disableFoo=selectedPage==“foo”
const disableBar=selectedPage==“bar”;
返回(
标题组件:{selectedPage}
onNavigationChange('foo')}>foo页面
onNavigationChange('bar')}>bar页面

); }; 类Foo扩展了React.Component{ 建造师(道具){ log('Foo构造函数'); 超级(道具); 此.state={ 当选主题:0 }; this.incrementTopic=this.incrementTopic.bind(this); } 递增主题(){ const{topicSelected}=this.state 常数newTopic=topicSelected+1 log(`incrementing topic:old=${topicSelected}new=${newTopic}`) 这是我的国家({ 主题:新主题 }) } render(){ log('Foo::render'); 返回( Foo内容页:topicSelected={this.state.topicSelected} 增量主题 ); } 组件willmount(){ log('Foo::componentWillMount'); } componentDidMount(){ log('Foo::componentDidMount'); } 组件将卸载(){ log('Foo::componentWillUnmount'); } componentWillUpdate(){ log('Foo::componentWillUpdate'); } componentDidUpdate(){ log('Foo::componentdiddupdate'); } } 常数条=(道具)=>{ log('Bar::render'); 返回酒吧内容页面 } const Body=(道具)=>{ log('Body::render'); const{selectedPage}=props; 如果(selectedPage==“foo”){ 返回; }else if(selectedPage=='bar'){ 返回 } }; 类应用程序扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 已选择页面:“foo” }; } render(){ log('Application::render'); const{selectedPage}=this.state; 常量导航更改=(下一页)=>{ 这是我的国家({ 所选页面:下一页 }) } 返回( ); } } ReactDOM.render(, document.getElementById('main') );

当用户从主页导航到t时,我认为您的主页正在卸载(销毁)