gpt4 book ai didi

javascript - react native 警告 : Cannot update during an existing state transition (such as within `render` )

转载 作者:行者123 更新时间:2023-11-30 13:52:02 25 4
gpt4 key购买 nike

如何摆脱这个警告?我知道我需要去掉 render 方法中的 setState 函数,但我需要它们,那么我应该把它们放在哪里呢?

export default class List<T> extends React.PureComponent<ListProps<T>> {
state = { wrapped: false, iconName: "arrow-down" };

render(): React.Node {
const { rows, renderRow, title, onPress } = this.props;
if (this.state.wrapped === true) {
list = undefined;
this.setState({ iconName: "arrow-up" });
} else {
list = rows.map((row, index) => (
<View key={index} style={index !== rows.length - 1 ? styles.separator : {}}>
{renderRow(row, index)}
</View>
));
this.setState({ iconName: "arrow-down" });
}
return (
<TouchableWithoutFeedback>
<View style={styles.container}>
<View style={[styles.separator, styles.relative]}>
<Text style={styles.title}>{title}</Text>
<IconButton
style={styles.icon}
onPress={() => this.setState({ wrapped: !this.state.wrapped })}
name={this.state.iconName}
color="black"
/>
</View>
{list}
</View>
</TouchableWithoutFeedback>
);
}}

最佳答案

不,您通常不需要在 render 方法中删除 setState 调用。您只需要放置它们,以便在每次渲染调用中都不会调用它们(通过将它们绑定(bind)到用户事件,例如点击),从而触发另一个重新渲染,再次调用 setState 并再次重新渲染-渲染等等。

因此,在您的特定情况下,您将在 if() { ... } else { ... } 语句的开头触发 setState 。无论 this.state.wrapped 是什么,您最终都会到达 setState

这里有一个可能的解决方案,说明您可能希望如何具体更改您的代码,以使其成为我假设您希望它成为的样子:

export default class List<T> extends React.PureComponent<ListProps<T>> {
state = { wrapped: false };

render(): React.Node {
const { rows, renderRow, title, onPress } = this.props;
const { wrapped } = this.state;

return (
<TouchableWithoutFeedback>
<View style={styles.container}>
<View style={[styles.separator, styles.relative]}>
<Text style={styles.title}>{title}</Text>
<IconButton
style={styles.icon}
onPress={() => this.setState({ wrapped: !wrapped })}
name={wrapped ? "arrow-up" : "arrow-down"}
color="black"
/>
</View>
{!wrapped && (
<View key={index} style={index !== rows.length - 1 ? styles.separator : {}}>
{renderRow(row, index)}
</View>
)}
</View>
</TouchableWithoutFeedback>
);
}}

因为你的icon的值是和wrapped直接相关的,所以你不需要专门设置状态下的icon。而是从 wrapped 推断它。

关于javascript - react native 警告 : Cannot update during an existing state transition (such as within `render` ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com