【发布时间】:2020-07-15 11:40:49
【问题描述】:
我在将状态传递给子组件时遇到了一个问题,所以基本上我从child1(Home) 获取客户信息并保存在父组件state(App) 中,它工作正常。
然后我将更新后的state(basketItems) 传递给child2(Basket)。但是当我点击 Basket 按钮时,购物篮页面不会在购物篮页面内的 console.log(basketItems) 中显示任何信息,并且 chrome 浏览器(控制台)看起来也刷新了。
任何建议为什么会发生以及如何优化以将数据从主(APP)传递到child2(basket)。
更新:2 我已经厌倦了用下面的链接模拟沙箱中的代码问题,非常感谢任何关于我在代码沙箱中的代码的建议(以使其更好),因为这是我第一次使用它
更新:1 我在 youtube 上做了一个小片段,只是为了了解我面临的问题 basketItems goes back to initial state
Main (APP)___|
|_Child 1(Home)
|_Child 2 (Basket)
来自Parent main(App) 组件的片段
function App() {
const [basketItems, setBasketItems] = useState([]);
const addBasketitems = (product, quantity) => {
setBasketItems(prevItems => [...prevItems, { ...product, quantity }])
}
console.log(basketItems) // here i can see the updated basketItems having customer data as expected [{...}]
return (
<Router>
<div className="App">
<header className="header">
<Nav userinfo={userData} userstatus={siginalready} />
</header>
<Switch>
<Route path="/" exact render={(props) => (
<Home {...props} userData={userData} userstatus={siginalready}
addBasketitems={addBasketitems}
/>
)}
/>
<Route path="/basket" exact render={(props) =>
(<Basket {...props} basketItems={basketItems} />
)}
/>
</Switch>
</div>
</Router>
来自child(basket)的片段
function Basket({basketItems}) {
console.log(basketItems) // here i only get the [] and not the cusotmer data from parent component
return (
<div>
{`${basketItems}`} // here output is blank
</div>
);
}
export default Basket;
来自child(Home)的片段
...这里一旦按下按钮,它会将用户选择的详细信息传递给父级
....
<Button name={producNumber} value={quantities[productName]} variant="primary"
onClick={() => {
addBasketitems(eachproduct, quantities[productName])
}}>
Add to Basket
</Button >
【问题讨论】:
-
您可以尝试创建一个代码框来重现您的错误吗?
-
嗨,Arpitha,老实说,我以前从未使用过代码沙箱,但如果可以的话,让我试试。如果有帮助,我也可以给你 Github 上项目代码的链接。 github.com/rock-007/Java-HTML-Project/blob/master/ec-client/src/…
-
创建codesandbox非常简单,如果您创建一个React Codesandbox,它将为您提供react的模板,您只需要专注于您可以从本地代码库中引入的代码。如果使用其他依赖项,只需单击“添加依赖项”即可添加它
标签: javascript reactjs react-router react-hooks