首页 > 解决方案 > 如何在 componentDidMount 中使用通过 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;

标签: reactjsredux

解决方案


这样做并做出反应将寻找用户

  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)),
    }
}



推荐阅读