gpt4 book ai didi

javascript - 使用 {...state} 创建仅修改一个字段的对象的新实例在 React JS 中不起作用

转载 作者:行者123 更新时间:2023-11-28 13:00:22 26 4
gpt4 key购买 nike

我正在开发一个简单的 React JS 应用程序。我正在使用 Redux。

我正在尝试修改 reducer 的状态并创建它的新实例并返回。但它抛出一个错误。

这是我的 reducer 代码:

export default function reducer(state={
tweets : [ "How are you doing" ],
name : ""
}, action){
switch(action.type)
{
case 'FETCH_TWEETS': {
return {...state, tweets: ["How", "are", "you", "doing"]};
}
}
return {...state};
}

正如你所看到的这一行:

return {...state, tweets: ["How", "are", "you", "doing"]}, 

我正在尝试更改 tweets 字段的值并创建该对象的新实例,其他字段保持不变。

但是,当我运行我的项目时,它给了我某种语法错误:

ERROR in ./src/app/reducers/tweetsReducer.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:/Users/Acer/Desktop/RealProject/src/app/reducers/tweetsReducer.js: Unexpected token (8:20)

6 | {
7 | case 'FETCH_TWEETS': {
> 8 | return {...state, tweets: ["How", "are", "you", "doing"]};
| ^
9 | }
10 | }
11 | return {...state};

那么,我的代码有什么问题吗?是否有其他方法可以仅修改对象的一个​​字段并创建新实例?

这是我的 package.json

{
"name": "realproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npm run build",
"build": "webpack -d && webpack-dev-server --content-base src/ --inline --hot --port 1234 --history-api-fallback"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"create-react-class": "^15.6.3",
"flux": "^3.1.3",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-redux": "^5.0.7",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"redux": "^4.0.0",
"redux-logger": "^3.0.6",
"redux-promise-middleware": "^5.1.1",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^4.13.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
}
}

这是我的 webpack.config:

var path = require('path');

module.exports = {

entry: path.resolve(__dirname, 'src') + '/app/index.js',
output: {
path: path.resolve(__dirname, 'dist') + '/app',
filename: 'bundle.js',
publicPath: '/app/'
},
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
query: {
presets: ['react', 'es2015'],
plugins: [ 'transform-decorators-legacy' ]
}
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
}
};

最佳答案

您需要transform-object-rest-spread babel plugin对于处于第 4 阶段的对象休息/传播属性。

关于javascript - 使用 {...state} 创建仅修改一个字段的对象的新实例在 React JS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51198257/

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