如何使用axios从json获取数据?

Enz*_*ss 5 javascript json reactjs redux axios

我正在尝试使用axios在表中获取JSON格式的服务器端数据,但无法理解如何获取每个字段,例如idcompanyInfo等等。

json:

[
  {
    "id": 1,
    "companyInfo": 1,
    "receiptNum": 1,
    "receiptSeries": "??",
    "customerName": "Mark",
    "customerSurname": "Smith",
    "customerMiddleName": "Jk",
    "customerPhone": "0845121",
    "services": [
      2,
      16
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

轴距:

 store.dispatch((dispatch) => {
dispatch({type: Actions.FETCH_DATA_START})
axios.get("http://localhost:3004/paymentReceipts")
  .then((response) => {
    dispatch({ type: Actions.RECEIVE_DATA, payload: response })
  }).catch((err) => {
    dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
  })
Run Code Online (Sandbox Code Playgroud)

减速器:

export const initialState = {
  paymentReceipts: []
};

export default handleActions<FetchData>({
  [Actions.FETCH_DATA_START]: (state, action) => {
    return ;
  },
  [Actions.FETCH_DATA_ERROR]: (state, action) => {
    return;
  },
  [Actions.RECEIVE_DATA]: (state, action) => {
      console.log("DONE WITH STATE");
    return {...state, 
        paymentReceipts :  action.payload
    }
  }
}, initialState)
Run Code Online (Sandbox Code Playgroud)

应用程式

@connect(mapStateToProps, mapDispatchToProps)
export class App extends React.Component<App.Props, App.State> {

  constructor() {
    super();
  }

  render() {
    console.log("CONTAINER IS ");
    console.log(this.props.receiveData);

    return (
      <div className={style.normal}>

      </div>
    );
  }
}

function mapStateToProps(state: RootState) {
  return {
    receiveData: state.receiveData
  };
}

function mapDispatchToProps(dispatch) {
  return {

  };
}
Run Code Online (Sandbox Code Playgroud)

这是我从中得到的 console.log

那么如何从JSON获取此值?

Piy*_*cha 7

您将把所有数据放入response.data

axios.get("http://localhost:3004/paymentReceipts")
  .then((response) => {
    dispatch({ type: Actions.RECEIVE_DATA, payload: response.data }) //Change
  }).catch((err) => {
    dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
  })
Run Code Online (Sandbox Code Playgroud)


Noc*_*ebo 6

要访问 json-response 中的单个属性,您只需执行以下操作:

response.data.<attribute>
Run Code Online (Sandbox Code Playgroud)

例如:

   axios.get("http://localhost:3004/paymentReceipts")
  .then((response) => {
    dispatch({ type: Actions.RECEIVE_DATA, payload: response.data, id: response.data.id }) //Change
  }).catch((err) => {
    dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
  })
Run Code Online (Sandbox Code Playgroud)

根据 json 的结构以及它的格式(例如对象数组),您必须遍历它。

  • 根据 [docs](https://github.com/axios/axios),您可以在 `response` 上调用几个关键字。例如:`response.data`、`response.status`、`response.headers` 等。我没有信心说这适用于所有环境和设置,但是是的,它是一个“关键字” `axios响应` (2认同)