ReactJS - setState不是函数

问题描述 投票:1回答:2

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

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

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

在函数内记录this验证函数是否正确绑定到我的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.
}
javascript reactjs
2个回答
2
投票

最好在反应组件创建时输入属性,如下所示:

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}的开始状态,你可以通过创建一个链接处理程序来扩展它!希望我能帮助你一点。


0
投票

如果您不喜欢在构造函数中进行手动绑定,则可以使用箭头函数。箭头函数自动绑定,不会出现与范围相关的问题

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'}) 
  }
© www.soinside.com 2019 - 2024. All rights reserved.