[英]Child Components not re-rendering despite a state-change in Parent
[英]JavaScript | ReactJS: Parent State-Change Not Triggering Child Props Update
render()
,但子组件的道具是静态的 这很简单。 我有一个具有状态属性和处理程序的<Parent />
。 父级将属性和处理程序都传递给子级。
子代有一个按钮,并调用其自己的处理程序,该处理程序包装了Parent的处理程序。 一个布尔值, isNew
,传递给家长-家长呼吁this.setState({ isNew: isNew })
父级始终调用render
并且在父级HTML中输出isNew
表示一切正确。 但是, <Child isNew={this.state.isNew} />
永远不会从this.props.isNew
输出正确的值-它始终是在Parent的getInitialProps
方法内部的Parent中初始化的值。
我刚刚参加了这个项目,但是我不相信我们正在其中实现Flux或Redux。 我的假设是,React开箱即用, 应将其道具设置为父状态的所有子代都重新渲染 。
换句话说,如果我具有以下条件:
React.createClass({
render: function () {
return (<Child isNew={this.state.isNew} handler={this.handler} />);
}
});
当父母从[状态改变]重新渲染时,所有依赖父母状态的孩子也应在将父母的新状态封装在其道具中的同时重新渲染。 假设<Child property={this.state.property} />
的子道具
我在这里完全缺少基本的东西吗?
请让我直接说:)
谢谢
我认为您在子构造函数中设置了this.props.isNew,然后尝试打印它。
大孩子:
import React, { Component } from 'react';
class GrandChild extends Component {
constructor(props) {
super(props);
this.toogle = this.toogle.bind(this);
}
toogle(e) {
if (e) {
e.preventDefault();
}
this.props.toogleParent(!this.props.isNew);
}
render() {
console.log('in grand child', this.props.isNew);
return (
<div>
<a onClick={this.toogle} href="">click</a>
</div>
);
}
}
export default GrandChild;
子组件:
import React, { Component } from 'react';
import GrandChild from './grand';
class Child extends Component {
render() {
console.log('in child', this.props.isNew);
return (
<div>
<GrandChild {...this.props} />
</div>
);
}
}
export default Child;
父组件:
import React, { Component } from 'react';
import Child from './child';
class MainPage extends Component {
constructor(props) {
super(props);
this.state = {
isNew: false
};
this.toogleParent = this.toogleParent.bind(this);
}
toogleParent(isNew) {
this.setState({ isNew });
}
render() {
console.log('in parent', this.state.isNew);
return (
<div>
<h3>Main page</h3>
<Child isNew={this.state.isNew} toogleParent={this.toogleParent} />
</div>
);
}
}
export default MainPage;
输出:
在父母中真实在孩子中真实在大孩子中真实
父母假子女假孙子女假
等等..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.