我是React Native的新手,尝试设置状态时出现“超过最大更新深度”错误。
在我的第一个屏幕中,我有一个textInput和一个用于扫描QR /条形码的按钮, 单击按钮会打开一个屏幕,在该屏幕上我扫描QR /条形码并发送回该值并将其设置为textInput。
下面是我的屏幕代码,我已经在注释中定义了我的问题。
//Screen1 => BarCodeScanning Screen1
// from BarCOdeScanning screen, i am returning the value like this
// which is working fine. the data is present in
// this.props.navigation.getParam("data).
// (able to fetch data in Second Screen)
handleBarCodeScanned = ({ type, data }) => {
this.props.navigation.navigate("IssueIMR", { data:data,
type:type });
};
//Screen2 => HomeScreen
constructor(props) {
super(props);
this.state = {
isLoading: true,
BarCodeValue : ""
};
}
render() {
const { navigate } = this.props.navigation;
const { navigation } = this.props;
//if i try to set state like below i am getting an error: maximum
// update depth exceeded
if(navigation.getParam("data")){
this.setstate({
BarCodeValue: navigation.getParam("data")
})
}
// I am able to get and store value of barcode like this. but i
// want to store the value in state.
var BarCodeValue = navigation.getParam("data");
return (
<View style={styles.container}>
<View style={{ marginTop: 10 }}>
<View style={CommonStyles.containerOne}>
<Text style={{ marginRight: 5 }}>Scan Bar Code</Text>
<TextInput
placeholder="Bar Code"
autoCapitalize="none"
// this onChangeText prop is only working when i am typing
// something manually, when i am setting the value in
// textfield from the response of screen, this function is
// not executing.
onChangeText={text => {
BarCodeValue = text;
}}
// And one more strange thing is happening...after getting
// the value of barcode from BarCodeScreen, when i am
// typing
// something manually, the value changes to the value i get
// after scanning the barcode. for ex, i get the value of
// barcode 12345, and set it to textInput, now if i add or
// remove
// any number to the textInput, it automatically sets to
// 12345, which i got from scanning the barcode.
value={BarCodeValue}
/>
<TouchableOpacity
style={styles.button_2}
onPress={() => navigate("ScanBarCode")}
>
<Text style={CommonStyles.buttonText}>Scan</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
答案 0 :(得分:0)
切勿在{{1}}方法内使用setState
。这将导致重新渲染循环,并且状态将再次更改。这是render
错误的原因。
从您的maximum update depth exceeded
方法中删除以下代码;
render
根据您的要求将此代码移至const { navigate } = this.props.navigation;
const { navigation } = this.props;
if(navigation.getParam("data")){
this.setState({
BarCodeValue: navigation.getParam("data")
})
}
var BarCodeValue = navigation.getParam("data");
或componentDidMount
等生命周期方法。
答案 1 :(得分:0)
我建议您尝试使用静态getDerivedStateFromProps(),如果那不起作用,请尝试
var x = "";
render()
{
if(x != navigation.getParam("data"))
{
this.setState({ BarCodeValue: navigation.getParam("data") })
x = this.state.BarCodeValue;
}
}
这将两次渲染您的屏幕。