Javascript 反应本机警告:无法在现有状态转换期间更新(例如在“呈现”中)
我如何摆脱这个警告?我知道我需要在render方法中去掉setState函数,但是我需要它们,那么我应该把它们放在哪里呢Javascript 反应本机警告:无法在现有状态转换期间更新(例如在“呈现”中),javascript,reactjs,react-native,Javascript,Reactjs,React Native,我如何摆脱这个警告?我知道我需要在render方法中去掉setState函数,但是我需要它们,那么我应该把它们放在哪里呢 export default class List<T> extends React.PureComponent<ListProps<T>> { state = { wrapped: false, iconName: "arrow-down" }; render(): React.Node { const { rows, rend
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>
);
}}
导出默认类列表扩展React.PureComponent{
state={wrapped:false,iconName:“arrow down”};
render():React.Node{
const{rows,renderRow,title,onPress}=this.props;
if(this.state.wrapped==true){
列表=未定义;
this.setState({iconName:“arrow up”});
}否则{
列表=行。映射((行,索引)=>(
{renderRow(行,索引)}
));
this.setState({iconName:“箭头向下”});
}
返回(
{title}
this.setState({wrapped:!this.state.wrapped})}
name={this.state.iconName}
color=“黑色”
/>
{list}
);
}}
不,通常不需要在render
方法中去掉setState
调用。您只需要放置它们,以便它们不会在每次渲染调用中被调用(例如,通过将它们绑定到用户事件,如单击),从而触发另一次重新渲染,再次调用setState
并再次重新渲染等等
因此,在您的特定情况下,您在if(){…}else{…}
语句的开始处触发setState
。不管这个.state.wrapped是什么,
以下是一个可能的解决方案,您可能希望如何专门更改代码,以使其符合我的假设:
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>
);
}}
导出默认类列表扩展React.PureComponent{
状态={wrapped:false};
render():React.Node{
const{rows,renderRow,title,onPress}=this.props;
const{wrapped}=this.state;
返回(
{title}
this.setState({wrapped:!wrapped})}
名称={已包装?“向上箭头”:“向下箭头”}
color=“黑色”
/>
{!包装&&(
{renderRow(行,索引)}
)}
);
}}
由于图标的值与wrapped
直接相关,因此无需专门将图标设置为状态。而是从包装的中推断出来