如何在componentDidMount中使用Redux获取的值

时间:2020-01-23 07:09:50

标签: reactjs redux

我试图在React + Redux中开发一个应用程序。我的问题是用Redux提取的值不能在componentDidMount()中使用。 Redux值仅在render()中使用,但是您有任何想法可以在渲染之前使用这些值。

我的代码:

class User extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { id } = this.props.match.params;
    this.props.fetchUser(id);

    const { user } = this.props;
    console.log("user", user);
    // This is my issue, I can't get user here!
  }

  render() {
    const { user } = this.props;
    console.log("user", user);
    return (
      <p>{user.name}</p>
    )
  }

function mapStateToProps({ users }) {
  return { user: users };
}

export default connect(mapStateToProps, { fetchUser })(User);

操作代码:

export function fetchUser() {
  return dispatch => {
    firebase.auth().onAuthStateChanged(user => {
      roomsRef
        .doc(user.uid)
        .get()
        .then(doc => {
          dispatch({ type: FETCH_USER, payload: doc.data() });
        });
    });
  };
}

减速器

import { FETCH_USER } from "../actions";

const initialState = {};

export default (state = initialState, action) => {
  switch (action.type) {
    case FETCH_USER:
      return action.payload;

    default:
      return state;
  }
};

商店

const rootReducer = combineReducers({
  users: UsersReducer,
});

const store = createStore(rootReducer, applyMiddleware(reduxThunk));
export default store;

2 个答案:

答案 0 :(得分:2)

执行此操作并做出反应将寻找用户

  state={
    user:null
  }

    componentDidMount = () => {
        this.props.fetchUser(id);
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.user !== prevState.user) {
            return { user: nextProps.user };
        }
        else return null;
    }

    componentDidUpdate(prevProps, prevState) {
        if (prevProps.user !== this.props.user) {
            //Perform some operation here
            this.setState({ user: this.props.user });
            // do what you wanna do with user here
             console.log(this.state.user) //would return user obj here
        }
    }

与Redux一样


const mapStateToProps = state => {
    return {
        user: state.UsersReducer.user
    }

}

const mapDispatchToProps = dispatch => {
    return {
        fetchUser: (id) => dispatch(actions.yourreduxfunc(id)),
    }
}


答案 1 :(得分:1)

您在fetchUser中对ComponentDidMount的实现是同步的。使其异步。

const { id } = this.props.match.params;

this.props.fetchUser(id).then(()=>{
    const { user } = this.props;
    console.log("user", user);
})