在this.setState()上没有调用render()
render() is not being called on this.setState()
我有一个简单的导航链接组件,在容器/表示类(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中的上下文绑定
相关文章:
- 在主干视图中调用render()方法的好方法
- ExpressJS在调用render方法时将数据发送到jade(现在称为pug)
- 对根组件中的一大组ReactDOM.render()调用进行分组
- Backbone.js在填充集合后调用render
- 调用render作为回调时访问视图属性
- 任何理由从外部调用Backbone.View.render
- 主干:调用扩展视图的覆盖 render() 函数
- 是否可以在从vanilla JS使用JSX时调用ReactDOM.render()
- 在 Express render() 中为函数调用获取未定义
- bundle.js中的多个reactDom.render调用
- 如何在发生更改事件时从编辑器视图调用单元格视图的render方法
- Backbone.js render()从未调用
- 为什么覆盖“控制器”$render `未被调用
- Rails:如何在render:pdf中从HTML调用Javascript函数
- 在teardown()之后调用render()不会显示列表数据
- 为什么我的render()函数在我的componentWillReceiveProps()之前被调用?
- 在BackboneJS中调用render()的合适方法
- 当render返回另一个组件时,React不会调用componentWillMount
- 在this.setState()上没有调用render()
- React Render调用两次,第二次未定义道具