Reactjs 获取获取数据后如何更新道具
我试图从fetch中获取数据,并使用新的道具“刷新”页面,这些道具的值就是fetch中的数据 提交=()=>{ }) render(){ 返回(Reactjs 获取获取数据后如何更新道具,reactjs,react-native,fetch,react-props,Reactjs,React Native,Fetch,React Props,我试图从fetch中获取数据,并使用新的道具“刷新”页面,这些道具的值就是fetch中的数据 提交=()=>{ }) render(){ 返回( {this.props.username} 我试图以某种方式接受responseJson并用它的值my props.username更新,但它似乎没有更新使用状态而不是道具 fetch("http://192.168.2.45/backend/public/api/update", { method: "POST", bo
{this.props.username}
我试图以某种方式接受responseJson并用它的值my props.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=>this.setState({username:responseJson}) )
.catch(error => console.error("error:", error));
<View style={{ alignItems: "center" }}>
<Text style={styles.name}>{this.state.username}</Text>
</View>
fetch(“http://192.168.2.45/backend/public/api/update", {
方法:“张贴”,
正文:JSON.stringify(用户),
标题:新标题({
“内容类型”:“应用程序/json”
})
})
.then(res=>res.json())
.then(responseJson=>this.setState({username:responseJson}))
.catch(error=>console.error(“error:,error));
{this.state.username}
道具是只读的,因此您不能从接收道具的组件中直接更新道具。状态是这样更改的机制。听起来好像您从父级获得了初始状态,因此您可以做一些不同的事情来处理
一件事是让您的获取在父组件中发生,更新父组件的状态,并将状态值作为道具传递给该组件。这样,道具和状态之间就不会发生冲突
另一种可能是,只要是真实的,就提供状态,否则就退回到道具上来
constructor(props) {
this.state = {
username: ""
}
}
render() {
return (
<View style={{ alignItems: "center" }}>
<Text style={styles.name}>{this.state.username || this.props.username}</Text>
</View>
)
}
(在所有这些情况下,在获取数据时都会更新状态,正如Roopak PutheVeettil在其评论中所说的那样。)
使用
componentdiddupdate()
和getDerivedStateFromProps()可以完成更复杂的事情
如果你真的需要合成一个更新状态和可以随时间变化的道具,但在这里你不需要。问题是我必须使用道具,因为在提交函数执行之前,我从父组件获取“this.props.username”。我不建议像这样从组件发出请求。设置延迟请求的本地状态是一种不好的模式/做法。我猜您指的是上面的家伙?因为我在fetch中没有使用setStaterequest@Vagtse是的,此评论是针对此答案的所有者的:)你使用的是像redux这样的状态管理框架吗?没有,因为我必须更新一些东西,这导致了很多问题…所以我只使用这个==>类父{…..render(){return您需要帮助设置吗?我想这也可以解决您的问题:)上面的一个人为我解决了问题,但仍然感谢队友:)是的!如果您有问题,请随时ping/提及我。
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=>this.setState({username:responseJson}) )
.catch(error => console.error("error:", error));
<View style={{ alignItems: "center" }}>
<Text style={styles.name}>{this.state.username}</Text>
</View>
constructor(props) {
this.state = {
username: ""
}
}
render() {
return (
<View style={{ alignItems: "center" }}>
<Text style={styles.name}>{this.state.username || this.props.username}</Text>
</View>
)
}
constructor(props) {
this.state = {
username: props.username
}
}