[英]React how to update the data in App.js from child component
I'm building a React App.我正在构建一个 React 应用程序。 I don't have a backend server.
我没有后端服务器。 Instead, I used a .json file called
securities.json
as the backend server.相反,我用一个叫做文件上传.json
securities.json
作为后端服务器。 The .json file list the securities and the price list in each security. .json 文件列出了每种证券的证券和价格表。
What I am attempting to do is to submit the updated price list to the securities.json on App.js, a parent component, from its child component.我试图做的是将更新的价目表提交给 App.js 上的 security.json,这是一个父组件,从它的子组件。 I noticed that when I add a new price in the Price Popup window and then close it but rechecked the Price Popup window again.
我注意到当我在价格弹出窗口中添加一个新价格然后关闭它但再次重新检查价格弹出窗口时。 The new price that I entered disappeared.
我输入的新价格消失了。 I couldn't figure out how to solve it.
我想不出如何解决它。 I'm trying to pass it up to App.js as one developer suggested.
我正在尝试按照一位开发人员的建议将其传递给 App.js。
Can someone please take a look at my code in CodeSandBox?有人可以看看我在 CodeSandBox 中的代码吗? https://codesandbox.io/s/github/kikidesignnet/caissa
https://codesandbox.io/s/github/kikidesignnet/caissa
Two solutions:两种解决方案:
Use Redux: https://react-redux.js.org/使用 Redux: https : //react-redux.js.org/
Use reacts context system: https://reactjs.org/docs/context.html使用 reacts 上下文系统: https : //reactjs.org/docs/context.html
you can also pass an update function as props to your child component which updates the state of the parent.您还可以将更新函数作为道具传递给您的子组件,以更新父组件的状态。
My guess is price list is set in constructor.我的猜测是价目表是在构造函数中设置的。 There the state is set from props.
那里的状态是从道具设置的。 On change of props, the price list state is not updated as setting state happens in constructor which executed only once.
在道具更改时,价格表状态不会更新,因为设置状态发生在仅执行一次的构造函数中。 You need to update state when ever props get changed.
你需要在道具改变时更新状态。
This is the code I am talking about这是我正在谈论的代码
constructor(props) {
super(props);
this.state = {
priceArr: this.props.pricelist,
// newPriceArr: this.props.updatePrice,
showPricePopup: false,
addPricePopup: false,
isToggleOn: true,
date: props.date || "",
number: props.number || ""
};
}
You may need to use getDerivedStateFromProps to set state when props change.您可能需要使用getDerivedStateFromProps来设置道具更改时的状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.