首页 > 解决方案 > 从子组件修改父数组 - React

问题描述

我正在构建一个 React 应用程序,我需要存储从应用程序打开的所有窗口的处理程序(是的,这有点奇怪,但这是我必须做的)。在使用 React 之前,我将窗口存储在附加到父窗口的全局数组中(我知道 JS 全局变量是一种非常糟糕的做法,但在项目中指定了这样做)。

我不想使用 Redux 并尝试仅使用 React 来解决这个问题。

在新的 React 应用程序中,我在 App 组件的状态上声明了这个数组,以及一个操作我作为道具传递给子组件的 stae 的方法:

class App extends Component {

  constructor(props) {
    super(props);
    this.state = { name: 'Desktop', openedWindows: [] };        

    this.handleStateChange = this.handleStateChange.bind(this)
  }  

   handleStateChange(param) {
     this.setState({
     openedWindows: [
       ...this.state.openedWindows,
       param
     ]
})

}

  render() {   
    const themes = ['#2c2f33', 'teal']
    const backgroundColor = themes[0]          

    return (
      this.state.name === 'Desktop' ?
      <div className='App'>
        <Header backgroundColor = {backgroundColor} />
        <Landing backgroundColor = {backgroundColor} 
          handleStateChange = {this.handleStateChange} />
        <Footer backgroundColor = {backgroundColor}/>
      </div>
      :
      <div className='App'>
        <Header backgroundColor = {backgroundColor} />
      </div>
    )
  }
}

export default App;

这是试图改变状态的子组件:

class Landing extends Component {
    handleOpenWindow = () => {     
        let newWindow = window.open('', '_blank')
        this.props.handleStateChange= this.props.handleStateChange.bind(this)
    }

    render () {
        const { backgroundColor } = this.props
        return (            
            <div className='landing'>
                <button className='btn' 
                    onClick={this.handleOpenWindow}
                    style={{backgroundColor}}
                >Abrir Editor
                </button>

            </div>
        )
    }
}

export default Landing

我得到一个 TypeError: Bind 必须在函数上调用

我在调用函数时尝试了不同的方法,但我无法让它工作。不知道我做错了什么,或者不使用 Redux 是否可行。

谢谢指教。

标签: javascriptarraysreactjs

解决方案


有2个问题:

构造函数中有一个错字:this.handleStateChange.bind.bind(this).bind太多了。

handleStateChange(param)状态更新是错误的:应该是

this.setState({
  openedWindows: [
    ...this.state.openedWindows,
    param
  ]
})

推荐阅读