升级到 React Native 26 后使用箭头函数时不再绑定

This is no longer bound when using arrow functions after upgrading to React Native 26

在我的项目中 this 在升级到 React Native 26 后使用箭头函数时不再绑定。

如果我在下面的示例中不使用 .babelrc,它可以使用箭头函数。添加 .babelrc 后,箭头功能不再起作用。

.babelrc

{ "passPerPreset": true, "presets": [ {"plugins":["../schema/babelRelayPlugin"]}, "react-native", ] }

我也试过:

{ "passPerPreset": true, "presets": [ {"plugins":["../schema/babelRelayPlugin"]}, "react-native-stage-0", ] }

{ "passPerPreset": true, "presets": [ {"plugins":["../schema/babelRelayPlugin"]}, "react-native", {"plugins":["transform-es2015-arrow-functions"]}, ] }


这个错误

class NoArrow extends Component {
  constructor(){
    super();
    this.state={x:0};
  }

  inc = ()=>{
    this.setState({x:this.state.x+1});
  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome} onPress={this.inc}>
          Welcome to React Native! {this.state.x}
        </Text>

      </View>
    );
  }
}

这有效

class NoArrow extends Component {
  constructor(){
    super();
    this.state={x:0};
    this.inc=this.inc.bind(this);
  }

  inc(){
    this.setState({x:this.state.x+1});
  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome} onPress={this.inc}>
          Welcome to React Native! {this.state.x}
        </Text>

      </View>
    );
  }
}

当adding/removing.babelrc也运行:


旁注:有趣的是,这甚至适用于 .babelrc

class NoArrow extends Component {
  constructor(){
    super();
    this.state={x:0};
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome} onPress={()=> this.setState({x:this.state.x+1})}>
          Welcome to React Native! {this.state.x}
        </Text>

      </View>
    );
  }
}



更新 1

删除$TMPDIR里面的缓存文件;它有一个散列名称,如 11acb28f1c8d3c6313ca5f8ccba3c158

使用 react-native-stage-0 可能修复了箭头函数问题,但现在 Relay.QL 不再正确编译。

{
  "passPerPreset": true,
  "presets": [
    {"plugins":["../schema/babelRelayPlugin"]},
    "react-native-stage-0"
  ]
}

不确定这是否真的与 26 有关,我与 25 有同样的问题。 在这里查看我的 post: Broken autobinding in arrow function for referenced node modules when using react-native with react-relay

对我来说,这个问题并没有持续存在,在修改了一段时间后,它就永远消失了。看起来 react-native-stage-0 为我做了。 清除缓存时,您唯一没有做的就是像这样清除 $TMPDIR:rm -rf $TMPDIR/react-*

我试图用示例项目重现我的问题,但没能成功,我也尝试 rm -rf node_modules,以确保万无一失。

我遇到了这个问题,但我很确定它早于 RN 0.24。你有什么版本的babel-core/babel-cli?我曾希望 T7191 能解决问题,但事实并非如此。

我最后做的是使用 babel-relay-plugin-loader。我不再使用 passPerPreset 了,它一直在可靠地工作,虽然我不完全明白它是如何工作的。

这是我的 .babelrc 现在的样子:

{
"presets": [
    "react-native"
],
"plugins": [
    "babel-relay-plugin-loader"
],
"env": {
    "web": {
        "presets": ["es2015", "stage-0", "react"],
        "plugins": ["babel-relay-plugin-loader"]
    }
}
}