React中setState处理程序的问题

时间:2017-06-08 14:11:17

标签: javascript google-chrome reactjs babeljs

我只是试图通过处理程序在react中更改组件的状态,但在执行函数时,状态不会改变。这里有handlers,state,setStates和我将处理程序作为属性

发送的组件

BTW:我正在使用带有babel装载机的webpack

export default class Game extends React.Component{
constructor(){
    super()
    this.state={
        pause: null
    }

}
PauseShow(){
    this.setState={ pause: "block" }
    console.log("pauseshow")
}
PauseHide(){
    this.setState={ pause: "none" }
    console.log("pausehide")
}
render(){

    return(
        <div className="big-box">
            <Player idc="Game" src="assets/Fly_Me_to_the_Aegis_Seven_Moon.mp3"/>
            <GameOutput/>
            <GameData pauseMethod={this.PauseShow.bind(this)}/>
            <GameInput />
            <GamePause display={this.state.pause} pauseMethod={this.PauseHide.bind(this)}/>

        </div>
    )
}

} Aquíllamoal un handlerquepaséporprops

export default class GameData extends React.Component{
constructor(){
    super()
}
render(){
    return(
        <div id="GameData">
            <button onClick={this.props.pauseMethod}>pause</button>
        </div>

    )
}

} 这里我们在控制台上显示错误,点击使处理程序执行的按钮

backend.js:8730 Uncaught TypeError:inst.setState.bind不是walkNode上的getData(chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8730:49)中的函数(chrome-extension:// fmkadmapgofadopljbjfkapdkoienihi / build / backend.js:8576:57)在chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15 at array.forEach(native)at walkNode(chrome-extension:// fmkadmapgofadopljbjfkapdkoienihi / build / backend.js:8578:20)在chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15 at array.forEach(native)at walkNode(chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js: 8578:20)在chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15 at Array.forEach(native)

2 个答案:

答案 0 :(得分:0)

您无法将状态更新为this.setState{pause: "block"}。您的状态是一个函数,您需要将对象作为参数传递给它。因此:

this.setState({pause: "block"})

是更新州的正确方法。

请参阅此代码:

class Test extends React.Component {
  constructor(){
      super();
      this.state = {
        text: ""
      }
  }
  pauseMethod(){
      this.setState({text: "paused"}, () => console.log(this.state.text))
  }

  render(){
    return (
        <div><GameData pauseMethod={this.pauseMethod.bind(this)} /></div>
      )
  }
}

class GameData extends React.Component{      
  render(){
      return(
          <div id="GameData">
              <button onClick={this.props.pauseMethod}>pause</button>
          </div>
      )
  }
}

React.render(<Test />, document.getElementById('container'));

Here is the fiddle.

答案 1 :(得分:0)

您可以更改this.setState({ pause: "none" })的{​​{1}}瞬间和其他状态

enter image description here

阅读文档的其他信息:Reactjs doc state modify