开发者问题收集

React js,无法读取属性“0”。调用 API 时

2018-01-29
79

我无法从 fetch 函数访问数据。我想将数据从操作传递到 Reducer。使用 fetch 函数调用 API,api 以承诺的形式返回。因此,API 被单独调用,数据返回给操作负载。

import { INDEX_PRESCRIPTION } from '../constant.js';

function fetch_prescription(){
  const base_url= "http://192.168.1.22:3000/api/v1/";
  const fetch_url = `${base_url}/prescriptions`;
  let datas = [];
  return fetch(fetch_url, {
    method: "GET"
  })
  .then(response => response.json())
  .then(data => {
    datas.push(data['prescriptions'])
    return datas
  })
}

export const indexPrescription = async () => {
  const action = {
    type: INDEX_PRESCRIPTION,
    details: await fetch_prescription()
  }
  return action;
  console.log('action details', action.details)
}

export const getIndexPrescription = (dispatch) => {
   dispatch(indexPrescription());
}

检查控制台时,我们得到:

在此处输入图像描述

如何访问处方详情。我尝试通过 action.details["0"]["0"] 访问它,但结果为“无法读取未定义的属性“0””。我已经经历了许多与此问题相关的问题和解决方案,但无法研究我的代码出了什么问题。

更新 这是我的 index.jsx 组件

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getIndexPrescription } from '../actions/index.js';

class Index extends Component {
  constructor(props){
    super(props);
    this.state = {
      prescription: null
    }
  }

  componentWillMount(){
    this.props.getIndexPrescription();
  }

  render(){
    return(
      <h2>
        Prescription Index
      </h2>
    )
  }
}

function mapDispatchToProps(dispatch){
  return bindActionCreators({ getIndexPrescription }, dispatch)
}

function mapStateToProps(state){
  return {
    prescription: state
  }
}

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

而我的 src/index.js 文件是

import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import {Provider} from 'react-redux';
import reducer from './reducers';
import Index from './components/index.jsx';

const store = createStore(reducer, applyMiddleware(thunk));

ReactDOM.render(
 <Provider store={store}>
    <Index />
 </Provider>, document.getElementById("root")
)
3个回答

仅当您收到服务器的答复后,您的承诺才会得到解决。您需要使用额外的层来处理 redux 中的 async 行为。

例如,使用 redux-thunk ,您可以使其像这样工作:

import { INDEX_PRESCRIPTION } from '../constant.js';
    
function fetch_prescription(){
  const base_url= "http://192.168.1.22:3000/api/v1/";
  const fetch_url = `${base_url}/prescriptions`;
  let datas = [];
  return fetch(fetch_url, {
    method: "GET"
  })
  .then(response => response.json())
  .then(data => data['prescriptions']);
}
    
export const indexPrescription = (dispatch) => {
  fetch_prescription()
     .then(details => {
          const action = {
              type: INDEX_PRESCRIPTION,
              details
           }
           
           dispatch(action);
  }
}
mavarazy
2018-01-29

您在此处遗漏的部分是函数 fetch_prescription() 是异步的。因此,当您访问数据时,数据可能不可用。

在解析 asnyc 函数 return datas 之前,您将返回 datas >

您可以将其用作

    import { INDEX_PRESCRIPTION } from '../constant.js';

    function fetch_prescription(){
      const base_url= "http://192.168.1.22:3000/api/v1/";
      const fetch_url = `${base_url}/prescriptions`;
      let datas = [];
      return fetch(fetch_url, {
        method: "GET"
      })
      .then(response => response.json())
      .then(data => {

        datas.push(data['prescriptions'])
        return datas
      })
    }

    export const indexPrescription = async () => {
      const action = {
        type: INDEX_PRESCRIPTION,
        details: await fetch_prescription()
      }
      return action;
    }

    export const getIndexPrescription = (dispatch) => {
       dispatch(indexPrescription());
    }

并在您想要的任何地方分派上述操作。

在 componentWillMount 中调用 getIndexPrescription()

Kodanda Rama Durgarao poluri
2018-01-29

找到下面的代码将 redux-thunk 添加到您的应用程序中。

...
import { createStore, applyMiddleware } from 'redux';
import reduxThunk from 'redux-thunk';
...

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers);

<Provider store={store}>
...
</Provider>
Shrey Kejriwal
2018-01-29