ReactJS -刷新时在componentDidMount中不能立即使用Props

ReactJS - Props not available immediately inside componentDidMount on a refresh

本文关键字:Props 不能 刷新 componentDidMount ReactJS      更新时间:2023-09-26

有一个令人沮丧的问题,希望有人能帮助。全面回购可在https://github.com/georgecook92/Stir/blob/master/src/components/posts/viewPosts.jsx。

直接进入代码-

componentDidMount() {
    const {user_id,token} = this.props.auth;
    this.props.startLoading();
    console.log('props auth', this.props.auth);
    if (user_id) {
      console.log('user_id didMount', user_id);
      this.props.getUserPosts(user_id, token);
    }
  }

如果组件是通过ui从另一个组件加载的,那么它将按预期运行。但是,如果页面被刷新,user_id等不能立即用于componentDidMount。

我已经检查过了,它是可用的以后,但我发现,如果我移动我的AJAX调用得到的帖子到一个渲染方法或其他生命周期的方法,如componentWillReceiveProps -道具正在不断更新,它锁定的UI -不理想。

我也不确定为什么每秒多个ajax调用正在进行,如果我将ajax调用移动到渲染方法。

我希望你能帮忙!谢谢你。

编辑。

    export function getUserPosts(user_id, token){
  return function(dispatch) {
    if (window.indexedDB) {
      var db = new Dexie('Stir');
      db.version(1).stores({
        posts: '_id, title, user_id, text, offline',
        users: 'user_id, email, firstName, lastName, token'
      });
      // Open the database
      db.open().catch(function(error) {
        alert('Uh oh : ' + error);
      });
      db.posts.toArray().then( (posts) =>  {
        console.log('posts:', posts);
        if (posts.length > 0) {
          dispatch( {type: GET_POSTS, payload: posts} );
        }
      });
    }
    axios.get(`${ROOT_URL}/getPosts?user_id=${user_id}`, {
      headers: {
        authorisation: localStorage.getItem('token')
      }
    }).then( (response) => {
      console.log('response from getPosts action ', response);
      dispatch( {type: GET_POSTS, payload: response.data} );
      dispatch(endLoading());
      response.data.forEach( (post) => {
        if (post.offline) {
          if (window.indexedDB) {
            db.posts.get(post._id).then( (result) => {
              if (result) {
                //console.log('Post is already in db', post.title);
              } else {
                //console.log('Post not in db', post.title);
                //useful if a posts offline status has changed
                db.posts.add({
                  _id: post._id,
                  title: post.title,
                  user_id: post.user_id,
                  text: post.text,
                  offline: post.offline
                });
              }
            } )
          }
        }
      } );
    })
      .catch( (err) => {
        console.log('error from get posts action', err);
        if (err.response.status === 503) {
          dispatch(endLoading());
          dispatch(authError('No internet connection, but you can view your offline posts! '));
        } else {
          dispatch(endLoading());
          dispatch(authError(err.response.data.error));
        }
      });
  }
}

我建议使用componentWillReceiveProps并将你的道具保存为状态,以便在发生变化时触发重新渲染(例如,道具从未定义变为具有值)。像这样可以工作:

import React, {Component} from 'react';
// using lodash for checking equality of objects
import _isEqual from 'lodash/isEqual';
class MyComponent extends Component {
    constructor(props={}) {
        super();
        this.state = props;
    }
    // when the component receives new props, like from an ajax request,
    // check to see if its different from what we have. If it is then 
    // set state and re-render
    componentWillReceiveProps(nextProps) {
        if(!_isEqual(nextProps, this.state)){
            this.setState(nextProps);
        }
    }
    render() {
        return (
            <div>{this.state.ItemPassedAsProp}</div>
        );
    }
}