简体   繁体   English

如何从 redux 存储中获取数据并在 React Native 的组件中使用它

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

I set up Redux with react native.我用本机反应设置了 Redux。 I manage to get the response from the backend in the action creator as res.data .我设法从动作创建者的后端获得响应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.注意这是我在 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只需删除渲染方法中的大括号(箭头 function 将直接以这种方式返回值),即

  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您可能在mapStateToProps中有错字,应该是state.request.requestData

The only thing I see is wrong is your mapStateToProps.我看到的唯一错误是您的 mapStateToProps。 Should be like this:应该是这样的:

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

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

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