在this.setState()上没有调用render()

render() is not being called on this.setState()

本文关键字:调用 render this setState      更新时间:2023-09-26

我有一个简单的导航链接组件,在容器/表示类(Smart/dumb)中分开,像这样:

我的表示组件:

import React, { PropTypes } from 'react';
class Navigation extends React.Component {
    componentWillReceiveProps() {
        console.log("here bro componentWillReceiveProps");
    }
    render() {
        console.log(this.props);
        var self = this;
        return (
            <div>
                <ul>
                    {
                        this.props.items.map( (m, index) => {
                            var style = '';
                            console.log("index", index, "focus", self.props.focused);
                            if(self.props.focused == index){
                                style = 'focused';
                            }
                            return <li key={Math.random()} className={style} onClick={self.props.clickHandler.bind(this, index)}>{m}</li>;
                        })
                    }
                </ul>
                <p>Selected: {this.props.items[this.props.focused]}</p>
            </div>
        );
    }
}
export default Navigation;

容器组件:

import React, {PropTypes} from 'react';
import Nav from '../components/Navigation';
class NavigationContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            focused : 0
        };
    }
    clicked(index) {
        this.setState({focused: index}, function () {
            console.log("set to", this.state.focused);
        });
    }
    render() {
        return (
            <Nav items={['Home', 'About', 'Contact Us']} clickHandler={this.clicked} focused={this.state.focused}/>
        );
    }
}
NavigationContainer.propTypes = {};
export default NavigationContainer;

当任何项(home, contact us…等)被点击并且状态被修改时,render()方法不会被再次调用,因此传递给哑组件的props是最新的。我的理解是,当状态发生变化时,则调用render()。我哪里做错了?

当你使用ES2015类语法extend React.Component时,你需要将你的操作处理程序绑定到你的类的上下文。

试试这个:

render() {
        return (
            <Nav items={['Home', 'About', 'Contact Us']} clickHandler={index => this.clicked(index)} focused={this.state.focused}/>
        );
    }

一般来说,最好不要在render中使用箭头函数或bind方法,因为它会在任何render调用上生成函数的新副本。将函数声明移到class constructor .

在这种情况下,我个人更喜欢使用箭头函数作为类属性

class MyClass extends React.Component {
  handleClick = () => {
    // your logic
  };
  render() {
    return (
      <button onClick={this.handleClick}>Click me</button>
    );
  }
}

这不是ES2015规范的一部分,但是babel stage-0预置支持此语法

你可以在这篇文章中了解更多React中的上下文绑定