redux 如何使用Axios从JSON中获取数据?

pexxcrt2  于 2023-06-23  发布在  iOS
关注(0)|答案(5)|浏览(122)

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

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})
  })

减速器:

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中获取这些值呢?

7dl7o3gd

7dl7o3gd1#

您将把所有数据都导入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})
  })
azpvetkf

azpvetkf2#

要访问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的结构和它的格式(例如。对象数组),你必须遍历它。

8ulbf1ek

8ulbf1ek3#

如果你收到的是文本而不是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})
}
31moq8wy

31moq8wy4#

import  Axios  from "axios";
import React ,{useState}from "react";
import { useNavigate} from 'react-router-dom';

const FrtchData = () =>
{
    const navigate = useNavigate();
const [emp,setEmp]=useState([])
Axios.get("https://fakestoreapi.com/products")
.then(res=>setEmp(res.data))

return (
    <div>

    {
        emp.map((emp,index) => <li key={index}>{emp.title}</li>)
    }
     <button onClick={()=>navigate("/home")}>Logout</button>
     
    </div>
)

}
export default FrtchData
wribegjk

wribegjk5#

import  Axios  from "axios";
import React ,{useState,useEffect}from "react";
import {useNavigate} from 'react-router-dom';

const FrtchData = () =>
{
    const navigate = useNavigate();
   
         const [users,setUsers] =useState([])
        useEffect (() =>{
            const asynfunc=async () =>{
                await Axios.get('https://fakestoreapi.com/products')
                .then(res=>setUsers(res.data))
            }
            asynfunc()
        },[])
        
        return (<div>
            {
                users.map((users,index) => <li key={index}>{users.title} </li>)
            }
            <button onClick={()=>navigate("/home")}>Logout</button>
        </div>)

}
export default FrtchData

相关问题