javascript - 在 React 初始化时 props 是未定义的。为什么?

标签 javascript reactjs react-360

我正在使用 React 360 创建一个 VR 应用程序。我想做的是最终创建一个应用程序,如下所示 Facebook VR multi surface example 。我正在获取该示例的代码,并尝试将其放入我的应用程序中。但是,我的 React 组件的以下初始化遇到了问题。

我有以下react-360应用程序,其代码为index.js

import React from 'react';
import connect from './Store';

import {
  asset,
  AppRegistry,
  StyleSheet,
  Text,
  View,
  VrButton,
} from 'react-360';

import Entity from 'Entity';


const ModelView = props => {

  *********** Problem **************
  Why are my props undefined if I am declaring it in the wrapper?
  **********************************

  return (
    <Entity
      style={{transform: [{scaleX: 1.25}, {scaleY: 1.25}]}}
      source={{obj: asset(`${props.planetName}.obj`), mtl: asset(`${props.planetName}.mtl`)}}
    />
  );
};

const ConnectedModelView = connect(ModelView);
export default ConnectedModelView;

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

从上面的代码中,我的 ModelView 的 props 不应该是未定义的。初始化时,它的值应该是earth

Prop 应该在Store.js中初始化。下面是代码:

import React from 'react';

const State = {
  planetName: 'earth'
};

const listeners = new Set();

export default function connect(Component) {
  return class Wrapper extends React.Component {
    state = {
      planetName: State.planetName
    };

    _listener = () => {
      this.setState({
        planetName: State.planetName
      });
    };

    componentDidMount() {
      listeners.add(this._listener);
    }

    componentWillUnmount() {
      listeners.delete(this._listener);
    }

    render() {
      return (
        <Component
          {...this.props}
          planetName={this.state.planetName}
        />
      );
    }
  };
}

从 facebook 代码中获取一个页面,我正在做的是通过 Store.connect 方法初始化模型 View 。此方法在 ModelView 周围创建一个包装器,我在其中通过 State.planetName 设置 Prop 。然而,我总是变得不确定,我不知道为什么。我已将代码中具有 State.planetName 的每个部分硬编码为 Earth 的值,但它仍然是未定义的。 Prop 没有设置为我想要的值,我不确定为什么。有人可以帮助我解释为什么会出现这种情况吗?我将不胜感激的帮助。

最佳答案

看起来您正在渲染 ModelView 而不是 ConnectedModelView

关于javascript - 在 React 初始化时 props 是未定义的。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53888800/

相关文章:

javascript - Angular 中的标题大小写在撇号后不大写

javascript - 如何将 JsonResponse 与 ajax 结合使用

javascript - React 中的状态正在返回到原始值

javascript - React Native,更改 React Navigation 标题样式

javascript - ReactVR如何正确设置指针(raycaster)

javascript - 为什么 moment.js 返回的日期是错误的?

javascript - Codeigniter 和 javascript-添加动态输入和单选字段

javascript - React JS .map 与 JSON 中的对象同时返回所有数据

javascript - ReactVR 中的事件处理