每次道具改变时都从孩子那里得到道具

  • 本文关键字:孩子 那里 改变 reactjs
  • 更新时间 :
  • 英文 :


所以在这种情况下`

getDataFromChild(val) {
this.setState({currentCurrency: val})
}
render() {
return (
<div className="App">
<Navbar sendData = {this.getDataFromChild} />
</div>`

我正在从Navbar子级获取数据并设置一个新状态,但当这些数据更改时,它不会更改父级的状态。我该怎么办?

我认为您想要做的事情必须在React中以不同的方式进行管理。

在react中,所有数据都向下流动(从父级流到子级(,而不是相反。如果子级具有父级需要的某些数据,那么它实际上应该是父级所具有的作为道具传递给子级的数据。(如果子级需要是更新数据的地方,那么父级应该向子级传递一个设置该状态的函数(。

即使您使用Redux(在Redux中,所有数据只有一个父Provider(,并且每个子级都会更改该父级(Singleton(的状态。所有儿童的一个数据来源。当使用React Redux时,您的应用程序看起来像:

return (
<ReduxProvider>
<App />
</ReduxProvider>
)

与Redux类似的是Providers的概念,其中有一个父组件,您可以在其中useState()或(useReducer()(并将dispatch/stateUpdater传递给该Provider的所有子组件。通常,您将该提供程序放在最顶层附近(它包装<App/>(。

使用提供商,您的应用程序看起来:

return (
<UserProvider> {/* contains user.id needed to get notifications */}
<NotificationsProvider> {/* makes a request like /api/{user.id}/notifications */}
<App /> {/* contains a navbar which displays all notifications */}
</NotificationsProvider>
</UserProvider>
)

即使你根本不想使用提供者(提供者的优点是你不必直接向每个子组件传递道具(,结构也必须保持不变——父组件必须向子组件提供道具(相反的做法可能会发生,但被认为是反模式(。

const App = () => {
const [notifications, setNotifications] = useState([]);
useEffect(() => {
// where we make an API req to get Notifications
getNotifications(setNotifications)
// then run setNotifications to what is returned from the API
}, []);
return (<div className="App">
<Navbar
notifications={notifications}
setNotifications={setNotifications}
/>
</div>);
}
const Navbar = ({ notifications, setNotifications }) => {
return (
<nav>
<div>{renderNotifications(notifications)}</div>
<button
onClick={
() => setNotifications([...notifications, newNotification])}
> Add Notification
</button>
</nav>
);

如果您使用提供者,则不必直接将道具从父对象传递给子对象:你的孩子可以做:

import { useNotifications, dispatch } from 'providers/notifications';
const Navbar = () => {
const notifications = useNotifications();
const [newNotification, setNewNotification] = useState();
const addNotifications = () => {
dispatch({type: 'ADD', payload: newNotification })
};
return (
<nav>
{renderExistingNotifications(notifications)}
<div>
<input
type='text'
value={newNotification}
onChange={e => setNewNotification(e.target.value)}
/>
<button onClick={() => addNotification()}>
Submit Notification
</button>
</div>
</nav>
);
}

最新更新