第一次提问竟然有这么多回复,总之感谢大家,可能是我有点思维定势了吧,过去编程一般我会在Controller读取设置并将它或它的一部分传递给相应Component,然后调对应Component的function来解决问题,所以我觉得单向的数据流没有什么问题,问题是react中的数据流是大概率会被改动的,这就需要一些状态逻辑,而SubComponent中状态逻辑的方法基本只能通过它自己JSX中事件的回调,换言之这些方法调用的位置被限定死了,所以我有点懵,在想这是不是故意设计来规避某些写法来的。
具体问题是我在用@material-ui的Snackbar,因为它的设置比较多,所以我稍稍封装了一下,这样就相当于有一部分状态在SubComponent中,而SubComponent本身又要暴露一部分状态在FatherComponent中,比如使用open来进行开关,然后我写了下面错误代码:
//SubComponent
function SnackBar(props) {
const [state, setState] = React.useState({
anchorOrigin: props.state.anchorOrigin || { horizontal: 'right', vertical: 'top' },
open: props.state.open || false,
Transition: props.state.Transition || Slide,
});
const handleClose = () => {
setState({
...state,
open: false,
});
};
return (
<Snackbar
open={state.open}
onClose={handleClose}
autoHideDuration={3000}
key={state.Transition.name}
>
<Alert onClose={handleClose} severity="success">
This is a success message!
</Alert>
</Snackbar>
);
}
//FatherComponent
function FatherComponent(props) {
// ...other code
return (
// ...other code
<SnackBar state={state}></SnackBar>
);
}
毫无疑问没有反应,因为这样SubComponent的state不会被更新,当时就想要是可以直接外部调用SubComponent的方法设置open就好...后来发现更新props也算副作用来的,需要用useEffect来更新,如果是class component应该是在componentWillUpdate加入setState的逻辑。
如果一定要在父组件调用子组件的方法,可能就是ref了,感谢大佬们~