基本上我想做的是停止在我的组件内部进行axios调用。所以我认为; “为什么不为此创建一个动作?”
我搜索了一下使用Redux的好“指南”,这就是我正在使用的内容:
所以我开始创建我的动作创建者:
import axios from 'axios'
import { CUSTOMER_FETCH } from './types'
import settings from '../settings'
axios.defaults.baseURL = settings.hostname
export const customers = () => {
return dispatch => {
return axios.get('http://hejhej/customers').then(res => {
dispatch({
type: CUSTOMER_FETCH,
data: res.data
})
})
}
}
稍后添加一个处理我的动作创建者的缩减器:
import { CUSTOMER_FETCH } from '../actions/types'
const initial = []
const customer = action => {
return {
data: action.data
}
}
const customers = (state = initial, action) => {
switch (action.type) {
case CUSTOMER_FETCH:
customers = [...state, customer(action)]
console.log('customers as state', customers)
return customers
default:
return state
}
}
export default customers
在我的组件内部我正在导入它:
import { customers } from '../../actions/customersAction'
稍后使用connect
:export default connect(null, { customers })(Events)
最后我在我的组件中使用它:
customers() {
this.props.customers(this.state.data)
}
所以我想知道我做错了什么,因为我在开发工具中看不到我的console.log。非常感谢阅读!
axios.get('http://hejhej/customers').then(res => {
this.setState({
res,
customer: res.data
})
})