redux 尝试将usedispatch挂接与userefs一起使用,但不起作用

kulphzqa  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(181)

我一直在试验Redux useDispatch钩子。我做了一个超级简单的应用程序,把笔记作为待办事项列表。直到现在useDispatch似乎对我不起作用,我得到了下面的错误:

Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\Users\Louaye Mandari\Desktop\redux-todo-list\redux-todo-list\src\App.js: Unexpected token, expected "," (17:26)

  15 |   const handleClicked = (e) =>{
  16 |     e.preventDefault();
> 17 |     dispatch(addTask({text.current.value}))
     |                           ^
  18 |   }
  19 |   return (
  20 |     <div className="App">

应用程序js

import { useSelector,useDispatch } from 'react-redux';
import taskSlice from './redux/taskSlice';
import './App.css';
import { useState,useRef } from 'react';
import { addTask } from './redux/taskSlice';

function App() {
  const data = useSelector(state=>state.tasks)
  const dispatch = useDispatch()
  const text = useRef()
  const handleClicked = (e) =>{
    e.preventDefault();
    dispatch(addTask({text.current.value}))
  }
  return (
    <div className="App"> 
      <button onClick={handleClicked}>
        Enter the new task 
      </button>
      <input type='text' ref = {text} placeholder='write the task here' />  
      <label>{data.task[data.task.length - 1]} </label>
    </div>
  );
}

export default App

任务切片.js:

import { createSlice } from '@reduxjs/toolkit';

export const taskSlice = createSlice({
  name: 'tasks',
  initialState: {
    task: ['hi'],
  },
  reducers: {
    addTask: (state, action) => {
      state.tasks.push(action.payload);
    },
  },
});

export const { addTask } = taskSlice.actions;
export default taskSlice.reducer;

存储.js

import { configureStore } from "@reduxjs/toolkit";
import taskReducer from "./taskSlice";

export const store = configureStore({
  reducer: {
    tasks: taskReducer,
  },
});

我正在尝试访问taskslice.js中reducers中的addtask。addtask应该转换新状态,并向任务数组的初始状态添加一个新元素。

e5njpo68

e5njpo681#

可能有多个问题,但第一个问题来自这一行

dispatch(addTask({text.current.value}))

{text.current.value}不正确。看起来您正在尝试执行object destructuring。请考虑addTask应该接受什么作为输入:一个字符串,一个对象,什么样的对象
为了关注解构错误,你要做的是:

const animal = { name: { first: "Rauli", last: "Cat" }, age: 7 }
console.log({animal.name.first})

这会给你错误Uncaught SyntaxError: Unexpected token '.'。在我的例子中,假设我只想记录名字,我可能想做类似这样的事情:

const animal = { name: { first: "Rauli", last: "Cat" }, age: 7 }
console.log(animal.name.first)

相关问题