我正在尝试通过render
方法进行状态更改,但它显示:
错误:超出最大更新深度。当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。 React限制了嵌套更新的数量,以防止无限循环。
class Test extends Component {
state = {
name:[],
}
render() {
this.setState({name:this.props.data})
return(
<div>
{this.state.name.map(e=>(
<h3>{e}</h3>
))}
</div>
);
}
}
答案 0 :(得分:1)
您不能在render函数中设置反应状态,但是可以在构造函数或大多数组件生命周期函数中设置。
在构造函数中设置一些初始状态
class Test extends Component {
constructor(props) {
super(props);
this.state = {
name: props.data,
};
}
render() {
return (
<div>
{this.state.name.map(e => (
<h3>{e}</h3>
))}
</div>
);
}
}
或在生命周期功能中设置状态
class Test extends Component {
state = {
name: [],
};
componentDidMount() {
this.setState({ name: this.props.data });
}
render() {
return (
<div>
{this.state.name.map(e => (
<h3>{e}</h3>
))}
</div>
);
}
}
答案 1 :(得分:0)
请不要在渲染函数中设置状态,因为它可能会产生副作用,并且最终将创建无限的渲染周期。每当状态发生变化时,React都会调用render()函数。在事件处理函数中的render函数外部进行设置状态,该事件根据用户与UI的交互而被调用。
下面的示例是一个基于功能的组件,当用户单击按钮时,该按钮会更改按钮的文本。
const DemoApp = (props) => {
const [state, setState] = useState(false);
const handleButtonPress = () => {
setState(true);
}
return(
<Button
onPress={handleButtonPress}
title={state ? 'Pressed' : 'click Here'}
color="#841584"
/>
)
答案 2 :(得分:0)
可能存在一种情况,其中一个对象的状态取决于一个不断变化的道具。在这种情况下,getDerivedStateFromProps 方法会很方便。在 this page 上给出了实现。以下是该方法的使用方法:
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));
此实现取自上述链接。它当然提供了在渲染方法中更改状态的替代方法。