javascript - 从子组件修改父数组 - 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 是否可行。
谢谢指教。
解决方案
有2个问题:
构造函数中有一个错字:this.handleStateChange.bind.bind(this)
这.bind
太多了。
在handleStateChange(param)
状态更新是错误的:应该是
this.setState({
openedWindows: [
...this.state.openedWindows,
param
]
})
推荐阅读
- mysql - 来自多个表 MySql 的单个查询
- react-native - React Native:如何将对象存储在 asyncstorage 中
- arrays - Excel vba使用前进和后退按钮逐步遍历数组
- c++ - 受保护成员 c++ 的默认值
- python - Python 简单测验程序 - 如何解决问题循环
- r - 如何从 R 中 PubMed 的数据框列表 MESH 列表中提取单词
- javascript - Javascript隐藏图片
- php - 如何解决“现有连接被远程主机强行关闭”的问题。从 Laravel 发送邮件时?
- google-apps-script - 通过 Google 脚本启用 Google 表格保护
- spring - @Async 和 @Transaction 方面顺序