我对react很新,我有问题bellow
我有这样的父组件:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {count:1};
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
return false;
}
setCount = () => {
this.setState({
count: 2
});
};
render() {
const {name, running, onRun, onStop} = this.props;
return (
<div>
<Test count={this.state.count}/>
<p><a href="#" onClick={this.setCount}>SetCount</a></p>
</div>
);
}
}
这是测试组件
class Test extends React.Component {
constructor(props) {
super(props);
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
return true;
}
render() {
const {count} = this.props;
return (
<div>
{console.log("Counting")}
<p>{count}</p>
</div>
);
}
}
i有方法" syse componentupdate"在父组件中返回" false",因为我不想重新渲染它。我的理解是React知道需要重新渲染DOM的哪一部分。在这种情况下,父母更改的状态将重新渲染"测试"组件
但是当我超过代码上方时,"测试"组件不会恢复。
我的代码中有什么问题吗?
非常感谢您的帮助
您需要从父母的shouldComponentUpdate
方法返回true
。
如果您返回false,则在初始渲染之后,即使调用调用setState
的函数。
您在谈论整个页面的刷新吗?如果这样,您可能想将<a>
标签更改为按钮或使用e.preventDefault();
。
如果没有,我不确定是否可能。如果您在父母中设定,它将与孩子一起养育父母。如果您不想渲染父母,则必须在子女级别管理单个状态管理。例如,
class Parent extends React.Component {
constructor(props) {
super(props);
}
render() {
const {name, running, onRun, onStop} = this.props;
return (
<div>
<Test/>
</div>
);
}
}
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {count:1};
}
setCount = (e) => {
e.preventDefault();
this.setState({
count: 2
});
};
render() {
const {count} = this.state;
return (
<div>
{console.log("Counting")}
<p>{count}</p>
<p><a href="#" onClick={this.setCount}>SetCount</a></p>
</div>
);
}
}