简体   繁体   English

React Redux不更新mapStateToProps中的组件状态

[英]React redux not updating component state in mapStateToProps

I'm new to react redux and really struggling to understand what is going on here. 我是新来应对redux的人,真的很努力地了解这里发生的事情。 If someone is able to shine a light on the situation I'd be very grateful. 如果有人能够对情况有所了解,我将不胜感激。

Here is my home screen: The thinking is, if the user has already logged in, then we show them this screen otherwise we navigate them to the log in screen. 这是我的主屏幕:想法是,如果用户已经登录,那么我们向他们显示此屏幕,否则我们将其导航到登录屏幕。 If they have signed in then we get all their info from the api and call setUser action. 如果他们已经登录,那么我们将从api中获取所有信息并调用setUser操作。

 const mapStateToProps = (state) => { return { user: state.userReducer[state.userReducer.length - 1], } } class HomeScreen extends React.Component { constructor(props) { super(props); this.state = { user: this.props.user }; } componentDidMount() { //Check if they've logged in already and set for redux. SecureStore.getItemAsync("USER_INFO").then(response => { if (response !== undefined && JSON.parse(response).id.length > 0) { fetch(WEB_API + '/api/getUserInfo/' + JSON.parse(response).id) .then(response => response.json()) .then(responseJSON => { console.log("setting user"); this.props.dispatch(setUser(responseJSON)); }) } else { const resetAction = NavigationActions.reset({ index: 0, actions: [ NavigationActions.navigate({ routeName: 'Login', params: this.props.navigation.state.params }), ] }); this.props.navigation.dispatch(resetAction); //this.props.navigation.navigate('Login'); } }); } render() { // } } }); export default connect(mapStateToProps)(HomeScreen); 

The setUser action can be found here and the reducer, they are in two separate files. 可以在此处找到setUser动作和reducer,它们位于两个单独的文件中。

 //UserReducer const userReducer = (state = [], action) => { switch (action.type) { case 'SET_USER': return [ ...state, { user: action.user } ] default: return state } } export default userReducer //userAction export const setUser = (user) => { return { type: 'SET_USER', user } } 

Lastly, in another component, I'm waiting to load a list of the user's preferences. 最后,在另一个组件中,我正在等待加载用户首选项的列表。 As such I need to wait for the user's information from redux. 因此,我需要等待来自redux的用户信息。 So in my ComponentWillReceiveProps function I have the following: 因此,在我的ComponentWillReceiveProps函数中,我具有以下内容:

 const mapStateToProps = (state) => { console.log(state); console.log("After mapping"); return { user: state.userReducer[state.userReducer.length - 1], } } class LinksScreen extends React.Component { static navigationOptions = { title: 'Challenges', }; componentDidMount() { } componentWillReceiveProps() { console.log("receiving"); console.log(this.props); console.log(this.state); fetch(WEB_API + '/api/getAs/' + this.props.user.user.id) .then(response => response.json()) .then(responseJSON => { this.setState({ a: responseJSON }) }); fetch(WEB_API + '/api/getBs/' + this.props.user.user.id) .then(response => response.json()) .then(responseJSON => { console.log(responseJSON); this.setState({ b: responseJSON }) }); } constructor (props) { super(props); this.state = { user: this.props.user, challengesToVerify: [], challengesToDo: [], } } render() { } } export default connect(mapStateToProps)(LinksScreen); 

I've put console.logs everywhere but I feel like I'm going around in circles, I just need the user in the LinksScreen to get the A's and B's. 我把console.logs放到了所有地方,但是我感觉好像在转圈,我只需要LinksScreen中的用户来获得A和B。 Redux is killing me! Redux杀死了我!

if you edit other screen this like that, ı think your structure is simple and easily read. 如果您这样编辑其他屏幕,则ı认为您的结构简单易读。

 const mapStateToProps = state => {
      const { user } = state.userReducer;
      return user;
    };

    class HomeScreen extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          user: this.props.user
        };
      }
      // Before component not render
      componentWillMount(){
        SecureStore.getItemAsync("USER_INFO").then(response => {
          if (response !== undefined && JSON.parse(response).id.length > 0) {
            this.props.getUserInfo(response);
          }
          else {
            const resetAction = NavigationActions.reset({
              index: 0,
              actions: [
                NavigationActions.navigate({ routeName: 'Login', params: this.props.navigation.state.params }),
              ]
            });
            this.props.navigation.dispatch(resetAction);
          }
        });
      }
      render() {
        // .....
      }
    }
    export default connect(mapStateToProps, { getUserInfo })(HomeScreen);


    // Action
    export const getUserInfo = (response) => dispatch => { // require redux-thunk for this dispatch
      fetch(WEB_API + '/api/getUserInfo/' + JSON.parse(response).id)
      .then(response => response.json())
      .then(responseJSON => {
        console.log("setting user");
        dispatch({
          type: 'GETUSERINFOSUCCESS',
          payload: { user: responseJSON}
        });
      })
    }


    // Reducer : userReducer

    const INITIAL_STATE = { 
      user: '',
    }

    export default (state = INITIAL_STATE, action) => {
      switch (action.type) {
        case "GETUSERINFOSUCCESS":
          return { ...state, user: action.payload.user };
        default:
          return state;
      }
    };

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

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