简体   繁体   中英

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.

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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