我正在尝试在带有axios的表中以JSON格式获取服务器端数据,但是无法理解如何获取id
,companyInfo
等所有字段。
json:
[
{
"id": 1,
"companyInfo": 1,
"receiptNum": 1,
"receiptSeries": "АА",
"customerName": "Mark",
"customerSurname": "Smith",
"customerMiddleName": "Jk",
"customerPhone": "0845121",
"services": [
2,
16
]
}
]
axios:
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})
})
reducer:
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 {
};
}
this is what i get from console.log
那么如何从JSON获取这些值?
答案 0 :(得分:5)
您将把所有数据都收录到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})
})
答案 1 :(得分:2)
要访问json响应中的单个属性,您只需执行以下操作:
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的结构及其格式(例如对象数组),你必须遍历它。
答案 2 :(得分:1)
如果您像我一样收到文本而不是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})
}
答案 3 :(得分:-3)
您可以在VUE中获取JSON,无需任何插件
var app = new Vue({
el: '#app',
// YOUR DATA HERE
data: {
filterResult: [] // THIS IS YOUR JSON FILE
},
// READY FUNCTION HERE
created: function() {
this.filterResult = this.dataResult();
},
// YOU FUNCTION HERE
methods: {
// CALLING API
dataResult: function() {
$.getJSON('/api/feature/stores/list', function(json) {
app.results = json;
app.filterResult = json;
});
},
}
});