gpt4 book ai didi

javascript - React js,无法读取属性 "0"。调用API时

转载 作者:行者123 更新时间:2023-12-03 02:37:00 25 4
gpt4 key购买 nike

我无法从获取函数访问数据。我想将数据从操作传递到 reducer 。使用fetch函数调用API,api以promise的形式返回。因此,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());
}

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

enter image description here

如何访问处方详细信息。我尝试通过 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")
)

最佳答案

只有在你得到服务器的答复后,你的 promise 才会得到解决。您需要使用额外的层来处理 redux 中的异步行为。

例如使用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);
}
}

关于javascript - React js,无法读取属性 "0"。调用API时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48496907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com