我的代码如下所示:
import { SAVE_SEARCH } from '../actions/index';
export default function (state = [], action) {
switch (action.type) {
case SAVE_SEARCH:
return [...state, action.payloadTwo, action.payloadOne];
default:
return state;
}
}
我在我的州里得到了这样的结果:
它可以工作,但这是一个数组。我想将其更改为object,如下所示:
case SAVE_SEARCH:
return [...state, { action.payloadTwo: action.payloadOne }];
因此,searchTerm将是对象中的键,数据将另存为对象键值。
但这段代码给了我一个错误:
我知道这对你来说很明显。为什么我不能这样编码?为什么会出现“分析错误”?
---------------
编辑:
非常感谢@marekful的回答!现在它工作了!
我的行动。js代码:
import axios from 'axios';
export const SAVE_SEARCH = 'SAVE_SEARCH';
export function searchTest(query) {
const githubApi = `https://api.github.com/search/repositories?q=${query}&sort=stars&order=desc`;
const request = axios.get(githubApi);
return (dispatch) => {
request.then(({ data: dataFromGithub }) => {
dispatch({ type: SAVE_SEARCH, payloadOne: query, payloadTwo: dataFromGithub });
});
};
}
减速器代码:
import { SAVE_SEARCH } from '../actions/index';
export default function (state = [], action) {
switch (action.type) {
case SAVE_SEARCH:
const o = {};
o[action.payloadOne] = action.payloadTwo;
return [...state, o];
default:
return state;
}
}
结果: