【问题标题】:ReactJS SetState not rerenderingReactJS SetState 不重新渲染
【发布时间】:2016-09-09 08:04:36
【问题描述】:

我有:

工作屏幕

handleSetView(mode, e) {
        this.setState({
            view: mode
        });
        console.log(this.state.view)
    }

    render() {
        return (

            <div className="jobs-screen">
                <div className="col-xs-12 col-sm-10 job-list"><JobList view={this.state.view} /></div>
                <div className="col-xs-12 col-sm-2 panel-container">
                    <div className="right-panel pull-right"><RightPanel handleSetView={this.handleSetView} /></div>
...
)
}

右侧面板

render() {
        return (
            <div>
                <div className="controls">
                    <span className="title">Views <img src="images\ajax-loader-bar.gif" width="24" id="loader" className={this.state.loading ? "pull-right fadeIn" : "pull-right fadeOut"}/></span>
                    <button onClick={this.props.handleSetView.bind(this, 'expanded')}><img src="/images/icons/32px/libreoffice.png" /></button>
                    <button onClick={this.props.handleSetView.bind(this, 'condensed')}><img src="/images/icons/32px/stack.png" /></button>
                    </div>
...
)}

工作清单

render() {
        var jobs = [];
        this.state.jobs.forEach((job) => {
            jobs.push(
                <Job key={job.id} job={job} view={this.props.view} loading={this.state.loading} toggleTraderModal={this.props.toggleTraderModal} toggleOFTModal={this.props.toggleOFTModal}/>
            );
        });

        return (
            <div>
                {jobs}
            </div>
        );
    };

问题是,视图状态的改变不会重新渲染任何子元素。

我怎样才能让它工作?

【问题讨论】:

  • 你有什么错误吗?
  • 没有错误。
  • 这不是状态不重新渲染你只是没有绑定你的函数的问题

标签: javascript reactjs fluxible


【解决方案1】:

不确定这是否是您问题的核心,但是:

handleSetView={this.handleSetView}

是错误的,因为 js 是如何绑定 this 的。使用:

handleSetView={this.handleSetView.bind(this)}

改为。

还有,

this.setState({
  view: mode
});
console.log(this.state.view)

看起来很奇怪;请注意,this.state 在您调用 setState 后不会立即修改,React 调度预定的 setState 操作可能需要一些时间。将 console.log 放入渲染中,看看它何时被实际调用。

最后,确保你的组件没有实现 shouldComponentUpdate 生命周期方法(你可能没有明确地这样做,但如果你的组件扩展了 React.Component 以外的某个类,这可能会发生)

【讨论】:

  • 天才 :) 我错过了 .bind(this)。这到底是做什么的?
  • :) 它确保this 在您调用handleSetView 时正确绑定到组件对象(这在js 中不会自动发生)
  • @Thomas Kulich 我确信这只是一个愚蠢的错误,但你说这不会在 js 中自动发生,我认为你的意思是在 ES2015 中。
  • 这不是处理这个问题的最佳方法,因为每次重新渲染都会创建一个新函数。最好在构造函数中绑定this.handleSetView或者转成es6箭头函数。
【解决方案2】:

this 在 react 组件的上下文中,所以要么将 this 的引用传递给你的函数 handleSetView,要么像 @Tomas 提到的那样绑定 this

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2019-12-13
    • 1970-01-01
    • 2022-01-06
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多