简体   繁体   English

我如何在反应中从 redux state 中提取数据

[英]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).我试图从 redux 发出 api 请求,然后将这些数据放入我的反应 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. api 调用有效,但我似乎无法在我的 app.js 上获取 state 以基于 redux Z8A35DA52ED10574E 调用进行更新。 Am i missing something?我错过了什么吗?

App.js应用程序.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.我认为你用 state 误导商店。 Your arrdata is empty since it's stored inside state, but your data comes from props.您的arrdata是空的,因为它存储在 state 中,但您的数据来自道具。

Anyways, arrdata in state remains empty, since you are not setting the state anywhere.无论如何, arrdata中的 arrdata 仍然为空,因为您没有在任何地方设置 state。 To do that, you would have to use eg getDerivedStateFromProps lifecycle hook, however I wouldn't recommend that.为此,您必须使用例如getDerivedStateFromProps生命周期挂钩,但我不建议这样做。

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.注意:实际上,您不需要 state。 It's a better approach to manipulate over props, instead of saving data from props into state (in most cases).这是操纵道具的更好方法,而不是将道具中的数据保存到 state(在大多数情况下)。

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

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