繁体   English   中英

React Native-this.setState不是一个函数

[英]React Native - this.setState is not a function

使用的技术:

问题:

this.setState不是函数。

码:

Router.js

export const Router = TabNavigator({
  ColorPicker: { screen: ColorPicker },
  Palette: { screen: Palette }
});

App.js

assignScreenType = screenType => {
  this.setState({
    currentScreen: screenType
  });
};

class App extends Component {
  render() {
    return (
    <Router
      screenProps={
        { state, updateRed, updateGreen, updateBlue, updateCyan, updateMagenta, updateYellow, updateBlack, calculateCMYK, calculateRGB, convertToHex, assignScreenType, renderSlider, saveColorSelection }
      }
    />
    );
  }
}

export default App;

Colors.js

<Button
  title="Test 1"
  onPress={ () => console.log((this.props.screenProps.assignScreenType))}
/>

<Button
  title="Test 2"
  onPress={ () => this.props.screenProps.assignScreenType('HEXScreen') }
 />

console.log显示的内容:

的console.log();信息

我尝试过的

  • 我已经将我的方法移到class App extends Component下方,并在render () {}上方。 这缓解了this.setState is not a function但随后引入了一个新的错误: ReferenceError: assignScreenType is not defined
  • 当该方法位于class App extends Component之下以及render () {}之上时,我尝试使用关键字this在代码的screenProps部分中传递assignScreenType ,例如: ...this.assignScreenType我收到了...this.assignScreenType的新错误this2.props.screenProps.assignScreenType不是函数,因为该方法现在未定义。
  • 我将我的方法移至render() {}并将该方法定义为常量。 这消除了所有错误,但是现在实际上没有任何动作。
  • 我试过使用constructor super(); 句法。
  • 我尝试过使用该方法,并将其放在class App extends Component之上,然后在Colors.js中调用该函数时,删除匿名函数包装() =>
  • 我已经通过Discord接触了React Native社区,也没有运气。

结果

到目前为止,我尝试过的任何操作都会导致以下错误之一: this.setState is not a function this.props.screenProps.assignScreenType is not a function -不执行任何操作。

我已经在这里呆了几个小时了,我没有运气。 我尝试了几种解决方案,曾尝试询问其他开发人员,也曾尝试询问Discord中的React Native社区。 仅使用React时传递props / state / ethods我没有问题,但是尝试通过React Navigation传递props / state / method对我来说不起作用。

你应该定义该方法的类,以便它会有正确this背景下,然后参考该方法在你的render与方法this.assignScreenType

class App extends Component {

  assignScreenType = screenType => {
    this.setState({
      currentScreen: screenType
    });
  };

  render() {
    return (
    <Router
      screenProps={
        { assignScreenType: this.assignScreenType, /* ...your other screenProps */ }
      }
    />
    );
  }
}

以下将无法正常工作,因为箭头功能根本没有上下文(aka this ):

 assignScreenType = screenType => {
   this.setState({

因此,使其成为常规函数:

 function assignScreenType( screenType) {
   this.setState({

然后执行以下操作:

  this.props.screenProps.assignScreenType('HEXScreen')

这在调用上下文为screenProps的函数时都screenProps ,您需要在screenProps更改上下文:

  this.props.screenProps.assignScreenType.call(this, 'HEXScreen')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM