我建立了这样的React页面:切换器已绑定到父组件的回调函数。回调更新父组件的状态。因此,当切换器单击时,父组件将重新呈现自己。 (由于某些特殊的用户请求,我无法在父组件之外创建它。)>
图像中的切换器是React-Switch库的一个组件:https://www.npmjs.com/package/react-switch
然后,当我单击切换台时,会出现警告:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the ReactSwitch component.
这里是一些代码段。在顶层页面:
// In the top-level page, there is a state to decide whether or not to apply some data filter onSwitcherClicked(event) { this.setState({ applyFilter: event, }); render() { const filter = this.applyFilter ? '{paths:["/some_filters"],}' : '{paths:["/none"],}'; return ( <div> <ComponentA filter = {filter} applyFilter = {this.applyFilter} callBack = {this.onSwitcherClicked} /> </div> );
在组件A中
// Component A componentWillMount() { // Send some API request according to this.props.filter and load the data // So every time the switcher clicked, the page will update the filter and pass some new props to componentA, // then ComponentA will remount it self } render() { return ( <div> <DataViewer> {/*A component to display the data*/} </DataViewer> <Switch onChange={this.props.callBack} checked={this.props.applyFilter}/> </div> ) }
我想是因为当我单击切换器时,它将重置其自身的状态。同时,父组件的状态也发生了变化。因此,当切换程序调用setState()时,其本身已被卸载。我对么?有一些解决方法吗?
谢谢!
我建立了这样的React页面:。切换器已绑定到父组件的回调函数。回调更新父组件的状态。因此,当切换台单击时,然后单击父级...
注释太长,但是您的组件结构应该看起来与这种情况非常相似,在这种情况下,您不会收到该警告。我有一种感觉,您可能正在尝试为国家复制真理的来源,而不是仅仅让它流下来。
const ParentComponent = () => {
const [isClicked,setIsClicked] = useState(false);
return (
...
<Switcher selected={isClicked} onClick={() => setIsClicked(!isClicked)}/>
)
}