[英]How to get data from JSON with Axios?
我正在尝试使用 Axios 在表中以 JSON 格式获取服务器端数据,但无法理解如何获取每个字段,如id
、 companyInfo
等。
json:
[
{
"id": 1,
"companyInfo": 1,
"receiptNum": 1,
"receiptSeries": "АА",
"customerName": "Mark",
"customerSurname": "Smith",
"customerMiddleName": "Jk",
"customerPhone": "0845121",
"services": [
2,
16
]
}
]
轴:
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})
})
减速机:
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)
应用程序
@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 {
};
}
这是我从console.log
得到的:
那么如何从 JSON 中获取这些值呢?
您将获得所有数据到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})
})
要访问 json-response 中的单个属性,您只需执行以下操作:
response.data.<attribute>
例如:
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})
})
根据 json 的结构以及它的格式(例如对象数组),您必须遍历它。
如果你收到的是文本而不是 JSON,就像我一样,
使用 async/await,它很简单,
let results = await axios.get("http://localhost:3004/paymentReceipts")
try {
let response = JSON.parse(results.request.response)
dispatch({ type: Actions.RECEIVE_DATA, payload: response })
} catch(err) {
dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.