![](/img/trans.png)
[英]React redux - parent state changing, but child components not re-rendering
[英]Changing the state in reactJs parent is not changing the props in react child components
我有一個Parent React組件,並且有3個子組件,我正在更改父組件的狀態,但是更改父組件的狀態並沒有更改子組件的道具。我將狀態從父組件傳遞給了子組件,但道具沒有在子組件內部進行更改。
我的父母
class Parent extends Component {
state = {
menuCategoryId:'',
}
handelOnClickRefundMenu = () => {
this.setState({menuCategoryId:''});
}
render() {
return (
<FoodMenu
menuCategories={menuCategories}
{...this.state}
/>
)
}
}
export default Parent;
子級1組件
class FoodMenu extends Component {
render() {
return (
<MenuCategories
MenuCategories={menuCategories.MenuCategories}
selectedMenuCategoryId={this.props.menuCategoryId}
/>
);
}
}
export default Child1;
子2組件
class MenuCategories extends React.Component{
render(){
const MenuCategories = this.props.MenuCategories;
const selectedMenuCategoryId = this.props.selectedMenuCategoryId;
const renderCategories = (MenuCategories) => (
MenuCategories ?
MenuCategories.map(card=>(
<MenuCategory
key={card._id}
{...card}
handleOnClickMenuCategory={this.props.handleOnClickMenuCategory}
selectedMenuCategoryId={this.props.selectedMenuCategoryId}
// propData={...this.props}
/>
))
:null
)
return (
<Fragment>
<div id="" className="food-menus-menu w-100">
<div className="row">
<OwlCarousel
className="owl-theme"
loop={true}
items={9}
autoplay={false}
autoplayTimeout={3000}
autoplayHoverPause={false}
nav={true}
navElement={'div'}
navText={[`<img src=${seventheenPng}>`,`<img src=${eitheenPng}>`]}
dots={false}
responsive={{
0:{
items:4
},
600:{
items:3
},
1000:{
items:7
}
}}
>
{MenuCategories ?
MenuCategories.length === 0 ?
<div className="no_result">
Sorry, no results
</div>
:null
:null}
{ renderCategories(MenuCategories)}
</OwlCarousel>
</div>
</div>
</Fragment>
)
}
};
export default MenuCategories;
兒童3組件
class MenuCategory extends Component {
render() {
const props = this.props;
console.log('The values of the props are not changing here')
console.log(props.selectedMenuCategoryId)
return (
<div className={`colCategory item`} onClick={()=>props.handleOnClickMenuCategory(props)}>
<button
className={`btn btn-primary w-100 py-2 d-inline-flex align-items-center justify-content-center ${props.selectedMenuCategoryId === props._id ? 'activeMenuCategory' : ''}`}>
{props.name}
</button>
</div>
);
}
}
export default MenuCategory;
當我在父類函數 handelOnClickRefundMenu中更改狀態時,在地圖函數 MenuCategory中的最后一個組件中的道具“ props.selectedMenuCategoryId”的值未更改
映射功能位於子組件2 MenuCategories中 。
請幫助我。
提前致謝。
關於使用生命周期方法強制重新渲染的所有答案都是錯誤的。 如果您正確傳遞了道具並且它們發生了變化,則子組件應自動重新渲染。
為了說明這一點, 這是一個快速的“骯臟”沙箱 ,其中有一個父級和兩個子級,可以根據需要向下傳遞道具。
我不知道您的代碼到底出了什么問題(我們可以運行和調試一個獨立的示例,這會有所幫助),但我建議將其解析為一個更簡單的情況,您可以從那里開始工作,然后從那里開始構建。
eta:您確定問題與點擊處理程序無關嗎? 您沒有將其傳遞給FoodMenu或MenuCategories。
為什么將prop和變量命名為與組件相同的名稱? 確實很難閱讀,並且可能導致您是引用組件還是prop /變量。 使用駱駝的情況
在組件MenuCategories中命名道具MenuCategories不僅是一種不好的做法,而且如果將其命名為menuCategories,則可以解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.