reactjs - 获取数据后如何更新 props

标签 reactjs react-native fetch react-props

我正在尝试从 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/

相关文章:

javascript - React Router 4 失败的上下文类型

javascript - React-Native android,重置默认应用程序

java - Hibernate Fetch 不再是 Join 的子类型

javascript - 传递的参数在函数和回调中未定义。在别处定义

android - React native - 开发服务器返回 respose 错误代码 :404

javascript - 中止上一个请求后无法发出新的获取请求

javascript - 即使未显式使用 `componentWillMount`,'componentWillMount' 警告仍可见

reactjs - 如何在react-spring中等待完成两个并行动画?

javascript - ReactJS:上传前预览多张图片

react-native - Redux-Persist 与 React-Native-Background-Fetch