gpt4 book ai didi

javascript - ReactJS - setState 不是函数

转载 作者:行者123 更新时间:2023-11-29 19:02:20 24 4
gpt4 key购买 nike

这里的类似问题似乎是范围界定问题的结果,但对我而言并非如此。我正在尝试创建函数处理程序来设置我的 App 组件的状态。这些绑定(bind)到 App 并存储以供重用。

createLinkHandler(link)
{
let pageState = this._pages[link];

this.linkHandlers[link] = (function(newState) {
this.setState({'page': newState});
}).bind(this._app, pageState);
}

在函数中记录 this 验证函数是否正确绑定(bind)到我的 App 组件。所以我做了一个简单的测试来验证 setState() 是否在正常情况下工作(main.js):

var myApp = <App/>
myApp.setState({'page': 1});

在上述两种情况下,我都得到了一个Uncaught TypeError: {this/myApp}.setState is not a function

this/myApp 的日志输出:https://s26.postimg.org/ejfxd1djd/Capture.png


更新(这是我的 App 类):

export class App extends React.Component
{
constructor(props)
{
super(props);

this.state = {
'page': this._pages.LOGIN,
'style': this._styles.DEFAULT
};
}

// etc.
}

最佳答案

最好像这样通过 React 组件创建输入属性:

class myApp extends React.Component {
constructor() {
super(this.props);

this.state = {
'page': this._pages.LOGIN,
'style': this._styles.DEFAULT,
...this.props // overrides defaults if existing
}
this.createLinkHandler = this.createLinkHandler.bind(this)
}

createLinkHandler(link)
{
// no underscore dongle
let pageState = this.pages[link];
// set new state only inside.
// do whatever you want to do over here.
this.setState({...state, xyz: 'test'})
}

render () {
return (
<NavBar { ...this.pages, this.createLinkHandler } />
)

}

}

class NavBar extends React.Component {

constructor(){
super(this.props)
this.state = { ...this.props }
}

render() {
// call on click the function this will then be executed in the app
// context and there you can change the App state.
<div>
<a OnClick={this.props.createLinkHandler('linkxyz')} />
<a OnClick={this.props.createLinkHandler('linkxyz')} />
<a OnClick={this.props.createLinkHandler('linkxyz')} />
</div>
}

}

// creating the react class with
// certain properties
const props = {page: 1}
var myApp = <App {...props} />

现在您有了一个包含 {page:1} 的起始状态,您可以通过创建链接处理程序来扩展它!希望我能帮到你一点。

关于javascript - ReactJS - setState 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45943299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com