[英]Why is child component not rerendering in React?
我需要幫助。 大量使用 Vue,第一次接觸 React。 我有一個父頁面組件,它有幾個子組件(頁面上帶有 forms 的塊)。 我遇到了一個問題,當改變子組件中的 switch-toggle 時,數據必須發送到父組件並且 state 必須在那里更改,並且這個 state 必須通過 props 傳回子組件。 並且子組件應該更改開關切換。 但它不會發生。 我究竟做錯了什么?
頁面組件(父級)
export default class SettingsPage extends Component<TProps, TState> {
state: TState = {
...
notifications: {
allCustomerTransactions: true,
...
},
...
};
...
onChangeNotifications = (field: keyof TNotifications, newValue: boolean): void => {
this.setState((state) => {
state.notifications[field] = newValue;
});
};
...
render() {
return (
<div>
...
<Notifications
className="cfx"
onChange={ this.onChangeNotifications }
notifications={ this.state.notifications }
/>
<hr className="b h1 mv55 bgDADCE1"/>
...
</div>
);
}
}
通知組件(子)
export default class Notifications extends Component<TProps> {
render() {
const {className, notifications, onChange} = this.props;
return (
<section className={ className }>
<div className="layoutRow fhaB fvaC">
<div className="f23 fw7 lts0em c0 wsNW ov tov wmin0 fx1">Notifications</div>
</div>
<div className="mt26 (w1/2|pr58|w@m|lt)>1">
<div>
<FormItem
name="Do you want to receive email notification for all customer transactions?"
className="mb27"
labelClasses="f12 fw4"
>
<SwitchB
checked={ notifications.allCustomerTransactions }
onChange={ (value) => {
onChange('allCustomerTransactions', value);
} }
/>
</FormItem>
...
</div>
</div>
</section>
);
}
}
您必須在您父母的 onchange function 中使用 currying function。閱讀更多: https://javascript.info/currying-partials
onChangeNotifications = (field: keyof TNotifications, newValue: boolean) => () => {
this.setState((state) => {
state.notifications[field] = newValue;
});
};
我找到了一個解決方案(雖然在我看來它看起來有點拐杖,因為 state 在父子組件中重復,但它工作得很好)
export default class Notifications extends Component<TProps, TNotifications> {
constructor(props) {
super(props);
this.state = { ...this.props.notifications }; // <-- new line
}
render() {
const {className, onChange} = this.props;
return (
...
<SwitchB
checked={ this.state.allCustomerTransactions } // <-- changed
onChange={ (value) => {
this.setState(() => ({ allCustomerTransactions: value })) // <-- changed
onChange('allCustomerTransactions', value);
} }
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.