我正在尝试在我的react项目中实现redux,但似乎无法解决遇到的这个问题。当我单击提交按钮时,我正在向我的减速器发出调度动作,在这种情况下,应该将道具“ loading”设置为true。我知道该操作被正确调用,因为在调用该操作时它将记录到控制台,但是没有来自reducer的日志(我已经将reducer编码为在调用它时进行记录)。但是,我可以看到以前的reducer在设置中被调用(初始调用等)。 这是我目前正在使用的我的减速器代码:
import { ADD_PRODUCT_STARTED, ADD_PRODUCT_SUCCESS, ADD_PRODUCT_FAILURE } from '../actions/types'
const initialState = {
products: [
{
name: 'Friends t-shirt',
price: '50',
img: 'https://static.bershka.net/4/photos2/2019/I/0/1/p/7337/058/250/7337058250_1_1_3.jpg',
id: 1
},
{
name: 'Computer',
price: '50',
img: 'https://cdn.def-shop.com/cdn-cgi/image/w=530,q=95,f=auto/images/product_images/picture1300x1725_images/619532_0.jpg',
id: 2
},
{
name: 'IPhone',
price: '50',
img: 'https://cdn.def-shop.com/cdn-cgi/image/w=530,q=95,f=auto/images/product_images/picture1300x1725_images/619532_0.jpg',
id: 3
}
],
loading: false,
error: null
};
const productsReducer = (state = initialState, action) => {
console.log(action.type, ADD_PRODUCT_STARTED)
switch (action.type) {
case ADD_PRODUCT_STARTED:
console.log('Reducing started...')
return {
...state,
loading: true
};
case ADD_PRODUCT_SUCCESS:
return {
...state,
loading: false,
error: null,
todos: [...state.todos, action.payload]
};
case ADD_PRODUCT_FAILURE:
return {
...state,
loading: false,
error: action.payload.error
};
default:
return state;
}
}
export default productsReducer
这是动作代码
import { ADD_PRODUCT_STARTED, ADD_PRODUCT_SUCCESS, ADD_PRODUCT_FAILURE } from './types'
const addProduct = (name, price) => {
return dispatch => {
console.log('Dispatching action...')
dispatch(addProductStarted)
console.log(`Action dispatched: ${addProductStarted}`)
// Perform actions here then: .then() => dispatch(addProductSuccess) and .catch() => dispatch(addProductFailure)
}
}
const addProductStarted = () => {
return {
type: ADD_PRODUCT_STARTED
}
}
const addProductSuccess = (product) => {
return {
type: ADD_PRODUCT_STARTED,
payload: {
...product
}
}
}
const addProductFailure= (err) => {
return {
type: ADD_PRODUCT_STARTED,
payload: {
...err
}
}
}
if(ADD_PRODUCT_SUCCESS && ADD_PRODUCT_FAILURE && addProductSuccess && addProductFailure){
console.log('Ignore thihihi')
}
export default addProduct
谢谢您的帮助,因为我真的为此感到困惑!
答案 0 :(得分:3)
您实际上并不是在分派动作。
此行是错误的:
dispatch(addProductStarted)
请记住,调度涉及将 action对象传递给dispatch
,例如:
dispatch({type: "increment"})
我们通常使用动作创建器功能来生成那些动作对象。这意味着您必须调用动作创建者才能获取动作对象:
const action = increment();
dispatch(action);
您不是呼唤动作创建者。您直接通过。
正确的语法是:
dispatch(addProductStarted())