有没有办法从父组件(都是函数组件)中刷新子组件状态?


function clearChildState(){
//Stuff to clear child state from parent components
}

我想要一个来自用户(谁看到父组件)的输入来单击一个按钮来清除子组件状态。怎么做呢?

可以将items传递为prop(parent->child)。

<Child items={items} />

子进程继续保持items状态,这是从itemsprop初始化的。
当父进程将一个空数组传递给子进程时,子进程的items状态将被重置为[]

这可以在基于类的子组件中使用getDerivedStateFromProps实现。

class Child extends React.Component {
constructor(props) {
super(props);
this.state = {items: []};
}
static getDerivedStateFromProps(props,state) {
return {items: props.items};
}   
// render
}

如果必须使用函数组件,则可以使用ref和effects来实现:

const ChildComponent = (props) => {

// Store your initial state
const initialState = {
name: 'Default Name',
title: 'Default Title'
}

const [{name, title} , setState] = React.useState(initialState)
const setNewState = () => {
setState({ name: 'New Name', title: 'New Title' })
}

// Use a ref to store the previous prop value
const prevClearChildStateCount = React.useRef(0)

// Use effects to run a check whenever the prop is updated
React.useEffect(() => {
if (props.clearChildStateCount > prevClearChildStateCount.current) {
setState(initialState)
}
prevClearChildStateCount.current = props.clearChildStateCount
}, [props.clearChildStateCount])

return (
<div>
<p>Name: {name}</p>
<p>Title: {title}</p>
<button onClick={setNewState}>Set new state</button>
</div>
)
}
const ParentComponent = () => {
const [clearChildStateCount, updateClearChildState] = React.useState(0)
const clearChildState = () => {
updateClearChildState(clearChildStateCount + 1)
}
return (
<div>
<ChildComponent clearChildStateCount={clearChildStateCount} />
<button onClick={clearChildState}>Clear Child State</button>
</div>
)
}
ReactDOM.render(<ParentComponent />, document.getElementById('container'))

链接到小提琴

最新更新