gpt4 book ai didi

javascript - ReduxReducer - 如何将此状态保存为对象? (我得到 "Parsing Error")

转载 作者:行者123 更新时间:2023-11-28 17:40:48 25 4
gpt4 key购买 nike

我的代码如下所示:

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

我在我的州得到了这样的结果:

enter image description here

它可以工作,但这是一个数组。我想将其更改为对象,如下所示:

    case SAVE_SEARCH:
return [...state, { action.payloadTwo: action.payloadOne }];

因此 searchTerm 将是对象中的键,数据将保存为对象键值。

但是这段代码给了我一个错误: enter image description here

我知道这对你来说是显而易见的。为什么我不能这样编码?为什么我收到“解析错误”?

<小时/>

--------------

编辑:

非常感谢@marekful 的回答!现在可以了!

我的action.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 });
});
};
}

reducer 代码:

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

结果:

enter image description here

最佳答案

在对象文字中,键只能是字符串文字(值可以是对象引用):{"someKey": object.property}

但是,您可以使用数组表示法将对象引用或函数返回值用作对象键(但它仍然必须是字符串):

let o = {};
o[action.payloadTwo] = action.payloadOne;
return [...state, o];

关于javascript - ReduxReducer - 如何将此状态保存为对象? (我得到 "Parsing Error"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47972352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com