作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何摆脱这个警告?我知道我需要去掉 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/
我是一名优秀的程序员,十分优秀!