无法读取setState
,print1
的值仍为0000
,必须更改为array[0] .date
并且警报显示 array[0].date
的值
问题是它以前有效。
PS:没有显示错误
export default class WebServiceUse extends Component {
constructor(props) {
super(props);
this.state = ({
print1: '0000',
})
}
componentDidMount() {
fetch('https://**********', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ id: '1' })
}).then((response) => response.json()).then((responseJson) => {
let array = responseJson.ed5aaf3d933385698d872d0a0d5d4f36
alert(array[0].date)
this.setState = ({
print1: array[0].date,
})
})
.catch((error) => {
console.error(error)
});
}
render() {
return (
<View style={styles.container}>
<Text>Test:</Text>
<Text>{this.state.print1}</Text>
</View>
);
}
}
最佳答案
当您在构造函数中设置状态时,this.state =
正在分配状态对象的初始值,因此它并不是真正的函数。在生命周期的更下游调用 this.setState
是一个将现有状态与更改合并的函数。所以改变一下
this.state = ({
print1: '0000',
})
至
this.state = {
print1: '0000'
}
此外,您没有分配状态,而是调用该函数,因此不要使用 =
this.setState = ({
print1: array[0].date,
})
应该是
this.setState({
print1: array[0].date
})
关于javascript - react native | setState无法读取的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54872765/