我正在调用API并且必须将这些操作传递给reducer。但来自行动的数据并未传递给减速器。我也没有使用联合减速机。
src / index.js是
import React from 'react';
import ReactDOM from 'react-dom';
import PrescriptionIndex from './components/prescriptionIndex.jsx';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<PrescriptionIndex />
</Provider>, document.getElementById("root")
)
这是我的组件PrescriptionIndex.jsx
import React, { Component } from 'react';
import { index_prescription } from '../action/index.js';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
class PrescriptionIndex extends Component {
constructor(props){
super(props);
this.state={
prescription: null
}
}
action_call(){
index_prescription();
}
render(){
this.state.prescription === null ? this.action_call() : null
return(
<div>
PrescriptionIndex
</div>
)
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({index_prescription}, dispatch)
}
function mapStateToProps( state ){
return {
profiles: state
}
}
export default connect(mapStateToProps, mapDispatchToProps)(PrescriptionIndex);
我在index_prescription();
中将索引函数称为action_call()
。
我的行动是
import {ADD_PRESCRIPTION} from '../constant.js';
import axios from 'axios';
import dispatch from 'axios';
export const index_prescription = () => {
const base_url= "http://localhost:3000/api/v1/";
const fetch_url = `${base_url}/prescriptions`;
axios.get(fetch_url)
.then(response => {
dispatch({type: ADD_PRESCRIPTION, details: response.data})
})
}
Reducer是
import {ADD_PRESCRIPTION} from '../constant.js';
const profiles = (state=[], action) => {
let profiles = null;
switch(action.type){
case ADD_PRESCRIPTION:
profiles = [...state, action.details]
return profiles;
default:
return state;
}
}
export default profiles;
constant.js是
export const ADD_PRESCRIPTION = "ADD_PRESCRIPTION";
我已经验证了所有questions,但无法在我的代码中研究出错。谢谢。
答案 0 :(得分:0)
您错过了以下代码..
import {ADD_PRESCRIPTION} from '../constant.js';
import axios from 'axios';
import dispatch from 'axios';
export const index_prescription = () => {
return dispatch=>{
const base_url= "http://localhost:3000/api/v1/";
const fetch_url = `${base_url}/prescriptions`;
axios.get(fetch_url)
.then(response => {
dispatch({type: "ADD_PRESCRIPTION", details: response.data})
})
}
}
&#13;
答案 1 :(得分:0)
你正在调用axions的派遣?不是react-redux的一部分吗?
如果您使用redux-promise-middleware
,则可以执行此操作:
import {ADD_PRESCRIPTION} from '../constant.js';
import axios from 'axios';
import dispatch from 'axios';
export const index_prescription = () => {
const base_url= "http://localhost:3000/api/v1/";
const fetch_url = `${base_url}/prescriptions`;
return {
type: "ADD_PRESCRIPTION",
details: axios.get(fetch_url)
.then(response => {
return response;
})
}
}