【问题标题】:React - this.state is empty in render when getInitialState is properly definedReact - 当正确定义 getInitialState 时,this.state 在渲染中为空
【发布时间】:2015-10-05 04:29:28
【问题描述】:

我会尽力解释这个场景,因为制作最小的可能情况可能很困难。本质上,我有一个使用 React-Router 的 SPA。我目前在特定版本的 Firefox (31.4esr) 中遇到了一种奇怪的行为。

我有两个侧边栏图标,它们触发路线更改,导航到新页面。有时当我在它们之间快速切换时,我会收到 this.state.list 未定义的错误(这是我用来填充下拉列表的列表)。

问题是,在调试时,console.log(this.state) 在我的渲染方法中调用(错误) this.state.list 之前返回一个空对象。但是,我在 getInitialState 中定义了列表(以及一堆其他状态变量),因此 this.state 绝对不应该为空。

我能想到的唯一会导致这种情况的原因是,如果由于快速切换而在安装/卸载组件时出现一些混淆,并且我的组件仍然认为它已安装,因此跳过 getInitialState 并继续尝试渲染。无论是那个还是 React-Router 中的一些错误。

有什么想法吗?提前感谢您的帮助!

尼克

P.S 我应该重申,这也只会在快速切换期间很少发生,并且通常 componentDidMount -> getInitialState -> 渲染会按预期发生,因此这不仅仅是我的 getInitialState 编写方式等方面的错误。

编辑:使用 React 0.13.3 和 React 路由器 0.13.3

编辑 2:这是生命周期方法的精简版,非常基本。

getInitialState: function() {
    return { list: listStore.getList("myList") || [] }
},

 render: function() {

var newList = [];
//this is the line that errors with this.state.list is undefined
this.state.list.forEach(function(listItem) {
    ...
}

return (
    <div>
        <OtherComponent newList={newList} />
    </div>
    )

};

将console.log放入componentWillMount(仅附加存储侦听器),getInitialState和render时,发生错误时会得到如下输出:

"Setting initial state"
"2,3" //This is this.state.list in componentWillMount
"2,3" //This is this.state.list in initial Render
Object { } //This is this.state the next time it gets called in render :S.

【问题讨论】:

  • 什么时候调试/记录状态?如果你把它记录在 componentWillMount 里面会说什么?
  • getInitialStatecomponentDidMount 之前被调用。 state 和 props 在挂载前都可用(参见componentWillMount)。
  • 你能告诉我们一些你的代码吗?至少是您正在使用的所有生命周期方法的精简版?
  • 太真实了......这使得调用渲染时状态的初始值不可用更加令人困惑。
  • 我现在无法访问代码,但明天我会检查并发布查找内容!

标签: javascript user-interface reactjs flux


【解决方案1】:

你必须像这样使用 mixin:

var state = {
 getInitialState: function() {
  return { list: listStore.getList("myList") || [] }
 }
}
var nameRouter = React.createClass({
  mixins : [state],
  // more content
})

这是因为 react-router 忽略了明确的 getInitialState

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多