简体   繁体   中英

How to get data from the redux store and use it in component in React Native

I set up Redux with react native. I manage to get the response from the backend in the action creator as res.data . But whenever I use it in my component it always evaluated to undefined or empty.

my action creator

export const getData = () => (dispatch: any) => {
  axios
    .get(`${API_URL}/api/request`)
    .then((res) => {
      dispatch({
        type: REQUESTS_FETCHED,
        requestData: res.data,
      });
      console.log(res.data);
    })
    .catch((err) => {
      console.error(err);
    });
};

And my reducer

const request = (state = initialState, action: any) => {
  switch (action.type) {
    case REQUESTS_FETCHED:
      return {
        ...state,
        requestData: action.requestData,
      };
    default:
      return state;
  }
};

The component as below

class Request extends Component {
  componentDidMount = () => {
    const {getData} = this.props;
    getData();
  };
  render() {
    const {requestData}: any = this.props;
    return (
      <View style={styles.container}>
        {requestData &&
          requestData.map((data: any) => {
              <Text>{data.value}</Text> 
          })}
      </View>
    );
  }
}

const mapStateToProps = (state: any) => ({
  requestData: state.request.requestdata,
});
const mapDispatchToProps = {
  getData,
};

export default connect(mapStateToProps, mapDispatchToProps)(Request);

NB this is the same code am using in reactjs. Thank you!

You need to return that text element. Just remove the curly brackets in your render method (arrow function will return the value directly this way), ie

  render() {
    const {requestData}: any = this.props;
    return (
      <View style={styles.container}>
        {requestData && requestData.map((data: any) => <Text>{data.value}</Text>)}
      </View>
    );
  }

You probably have typo in the mapStateToProps it should be state.request.requestData

The only thing I see is wrong is your mapStateToProps. Should be like this:

const mapStateToProps = (state: any) => ({
    requestData: state.requestdata,
});

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