简体   繁体   English

为什么我无法在reactjs中的渲染中访问组件状态

[英]Why I can't access component state in render in reactjs

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. 尝试学习react.js时,我试图在getInitialState设置组件的状态并使用this.state.myproperty在渲染中访问它,但似乎我做错了什么。

app.jsx this is my entry point app.jsx这是我的切入点

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

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

/components/App.jsx /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;

Action creator 动作创作者

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 ? 为什么我不能从州访问users ,或者我做错了方法?

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. 它是商店中必须聆听调度员的商店。

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. 如果我是你,我将在getInitialState中返回一个模拟对象,将组件订阅UserStore更改事件,并在商店告诉我后获取用户数据。

And then I would update the component state(using setState method) at the UserStore subscription's callback. 然后,我将在UserStore订阅的回调中更新组件状态(使用setState方法)。 setState method will call render automatically. setState方法将自动调用render。

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

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