我正在尝试从 fetch 获取数据,并使用新的属性“刷新”页面,它们的值是来自 fetch 的数据
提交 = () => {
let user = {
email: this.props.email,
newuser: this.state.new_username
};
fetch("http://192.168.2.45/backend/public/api/update", {
method: "POST",
body: JSON.stringify(user),
headers: new Headers({
"Content-Type": "application/json"
})
})
.then(res => res.json())
.then(responseJson=>Actions.refresh({username:responseJson}) )
.catch(error => console.error("error:", error));
};
渲染() { 返回(
<View style={{ alignItems: "center" }}>
<Text style={styles.name}>{this.props.username}</Text>
</View>
我正在尝试以某种方式获取 responseJson 并使用其值更新我的 props.username ,但它似乎没有更新
最佳答案
Prop 是只读的,因此您无法从接收它们的组件中直接更新它们。状态是此类变化的机制。听起来您正在从父级获得初始状态,因此您可以采取一些不同的措施来处理该状态。
一件事是让您的提取发生在父组件中,更新父组件的状态,并将状态值作为 Prop 传递给该组件。这样 props 和 state 之间就不会发生冲突。
另一种可能性是仅提供状态(如果状态为真),否则返回到 props。
constructor(props) {
this.state = {
username: ""
}
}
render() {
return (
<View style={{ alignItems: "center" }}>
<Text style={styles.name}>{this.state.username || this.props.username}</Text>
</View>
)
}
这是一种基本上可行的方法,但 React 不推荐。
constructor(props) {
this.state = {
username: props.username
}
}
(在所有这些情况下,您都会在获取数据时更新状态,正如 Roopak PutheVeettil 在他们的评论中所说。)
如果您确实必须合成可随时间变化的更新状态和属性,则可以使用 componentDidUpdate()
和 getDerivedStateFromProps()
执行更复杂的操作,但你在这里不应该需要它。
关于reactjs - 获取数据后如何更新 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56467743/