为什么我无法在reactjs中访问渲染中的组件状态 [英] Why I can't access component state in render in reactjs

查看:94
本文介绍了为什么我无法在reactjs中访问渲染中的组件状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试学习react.js我试图在 getInitialState 中设置组件的状态,并使用 this.state在渲染中访问它。 myproperty 但似乎我在做一些愚蠢的错误。这就是我到目前为止所做的。

Trying to learn react.js I was trying to set the state of the component in getInitialState and access it in render using this.state.myproperty but seems I am doing something silly wrong .Here is what I have done so far.

app.jsx
这是我的切入点

app.jsx this is my entry point

var React = require('react');
var App = require('./components/App');

React.render(
  <App />,
  document.getElementById('content')
);

/components/App.jsx

var React         = require('react');
var UserStore     = require('../stores/UserStore');
var ActionCreator = require('../actions/Actions');
var UserApp       = require('./UserApp');
var App = React.createClass({

  propTypes: {
     users: React.PropTypes.array,
   },

 getInitialState: function() {
      ActionCreator.loadUsers();
      return UserStore.getState();
  },

  render: function(){
    var users = this.state.users;
     console.log(this.state);// see what is in the state
     console.log(users);  // see what is in users 
     return(
        <UserApp users = {users}/>
     );
  },
});


module.exports = App;

行动创建者

var AppDispatcher = require('../dispatcher/AppDispatcher');
var Constants = require('../constants/Constants');
var ApiClient = require('../clients/ApiClient');
var ActionTypes = Constants.ActionTypes;
var Actions = {

  loadUsers: function(){
     ApiClient.getUsers(function(usersObj) {
       AppDispatcher.handleServerAction({actionType:ActionTypes.LOAD_USERS_SUCCESS, usersObj: usersObj});
     }.bind(this), function(error) {
      AppDispatcher.handleServerAction({actionType:ActionTypes.LOAD_USERS_FAIL, error: error});
     }.bind(this));
   },
};

module.exports = Actions;

这是我在控制台中看到的内容

Here is what I see in console

为什么我能'从状态访问用户或我是否以错误的方式进行操作?

Why I can't access users from state or am I doing it in wrong way ?

推荐答案

在通量理论上,您的组件必须调用操作并等待存储通知数据已准备就绪。它是必须监听调度程序的商店。

On flux theory your component must call an action and wait for the store to notify the data is ready. It is the store the one which has to listen to the dispatcher.

如果我是你,我会在getInitialState中返回一个模拟对象,将我的组件订阅到UserStore更改一旦商店告诉我,就获取用户数据。

If I were you I would return a mocked object in the getInitialState, subscribe my component to the UserStore change event and get the user data once the store tell me to.

然后我会在UserStore订阅的回调中更新组件状态(使用setState方法)。 setState方法将自动调用render。

And then I would update the component state(using setState method) at the UserStore subscription's callback. setState method will call render automatically.

这篇关于为什么我无法在reactjs中访问渲染中的组件状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆