在React 360中使用React上下文-不变违规:元素类型无效

时间:2018-10-13 16:27:39

标签: javascript reactjs react-360 react-context

我正在使用React 360开发一个VR应用程序,为了更新世界,我需要使树深处的组件可以使用回调。我不想在树上一直传递回调,所以我尝试了React Context,但是我一直收到以下错误: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

这是我的代码:

创建React上下文

import React from 'react';

export const CurrentWorld = React.createContext({
    updateWorld: () => {}
});

index.js文件

import React from 'react';
import {
  View,
  AppRegistry,
  NativeModules,
} from 'react-360';
import ReactDOM from 'react-dom'
import {CurrentWorld} from './Context/CurrentWorld'
import LoadWorld from './World/LoadWorld'
import LoadingMessage from './Helpers/LoadingMessage'
console.log(CurrentWorld)
// get something similar to window.location
const Location = NativeModules.Location;

export default class BoxApp360 extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      worldID: null,
    }
  }

  componentWillMount() {
    this.getParamsFromUrl()
  }

  render() {
    // console.log(this.state.worldID)
    return (
      <View>
        {(null === this.state.worldID)
          && <LoadingMessage />}

        {(0 === this.state.worldID)
          && <LoadingMessage message="Looks like there is no world to load" />}

        {(null !== this.state.worldID)
          && (0 !== this.state.worldID)
          && <CurrentWorld.Provider value={{
                updateWorld: this.updateWorld.bind(this)
              }}>
              <LoadWorld
                worldID={this.state.worldID}
                onWorldUpdate={this.updateWorld.bind(this)} />
            </CurrentWorld.Provider>}
      </View>
    );
  }

  updateWorld(newID) {
    // console.log(newID)
    this.setState({worldID: newID})
  }

  getParamsFromUrl() {
    if (Location.search) {
      // load the word id
      const worldParam = Location.search.match(/worldID=([0-9]*)/)
      if (null !== worldParam) {
        this.setState({
          worldID: worldParam[worldParam.index]
        })
      }
    } else {
      this.setState({
        worldID: 0
      })
      console.warn('We do not have a word ID')
    }
  }
};

AppRegistry.registerComponent('BoxApp360', () => BoxApp360);

导入后的console.log显示this error message(这告诉我ReactContext已成功创建)。

如果我删除了CurrentWorld.Provider组件,则LoadWorld可以正常工作,并且该应用程序可以按预期运行。

我想念什么?我不能在React 360中使用React Context(我的意思是React是对的吗?上下文是其中的一部分)吗?

由于React Context是React附带的,所以我想避免使用Redux,而我只需要为较低的组件提供一个回调即可。听起来几乎没有理由包括一个新的依赖关系。但是在这一点上,我应该放弃并使用Redux吗?

感谢您的帮助!

0 个答案:

没有答案