Why I can't access component state in render in reactjs

纵然是瞬间 提交于 2019-12-08 04:23:29

问题


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 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;

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 ?


回答1:


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.

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



来源:https://stackoverflow.com/questions/28660605/why-i-cant-access-component-state-in-render-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!