简体   繁体   中英

How do i pull data from redux state in react

Im trying to make an api request from redux then take that data and put it in my react state (arrdata). The api call works but i cant seem to get the state on my app.js to update based on the redux api call. Am i missing something?

App.js

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      arrdata: []
    };
  }
  componentDidMount() {
    this.props.loadData();
    console.log(this.props.data);
  }
  render() {
     const {arrdata} = this.state
    return ( ......)}}


const mapStateToProps = state => {
  return {
    data: state.data
  };
};

export default connect(mapStateToProps, dataAction)(App);

Action

export function loadData() {
  return dispatch => {
    return axios.get("https://api.coincap.io/v2/assets").then(response => {
      dispatch(getData(response.data.data.slice(0, 10)));
    });
  };
}

export function getData(data) {
  return {
    type: "GET_DATA",
    data: data
  };
}

Reducer

let initialState = {
  data: []
};

const mainReducer = (state = initialState, action) => {
  if (action.type === "GET_DATA") {
    return {
      ...state,
      data: action.data
    };
  } else {
    return {
      ...state
    };
  }
};

export default mainReducer;

I think you are misleading store with state. Your arrdata is empty since it's stored inside state, but your data comes from props.

Anyways, arrdata in state remains empty, since you are not setting the state anywhere. To do that, you would have to use eg getDerivedStateFromProps lifecycle hook, however I wouldn't recommend that.

render() {
   const { data } = this.props;
   console.log(this.props.data);

   return (
     // do something with your data
   );
}

It should log your data properly.

Note : You don't need state, actually. It's a better approach to manipulate over props, instead of saving data from props into state (in most cases).

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