变量名称未定义错误。我尝试将商店名称(注册信息)存储在redux商店中[重复]

问题描述 投票:0回答:1

我想将我的登录凭据存储在 redux-react 中。我附加了几行代码(问题的一部分)。

sksignup.js:

import React, { Component } from 'react';
import { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { connect, useDispatch, useSelector } from 'react-redux';
import { namesactions } from '../store/display';

function Sksignup() {
  const[shopname,setshopname]=useState('') 
  const dispatch = useDispatch()

  const showdetails =(e) =>{
        setshopname(e)
        dispatch(
            namesactions.updatename(
                {   
                    type: "namesactions",
                    payload: {shopname},
                }
            )
        )
    }
   

  const insertdata = () => { #backend code that works fine
    axios.post('http://localhost:3001/register', { shopname: shopname, })
      .then( 
        navigate('/userentry')
      ) 

  <label>enter your shop name:</label>
  <input type="text" name="shopname" onChange={(e)=>{showdetails(e.target.value)} />
  <button onClick={insertdata}>register</button>

与 store 相关的代码(创建用于存储与 redux 相关的文档)文件夹

display.js\store:

import { configureStore, createSlice } from "@reduxjs/toolkit";

const names = createSlice({
  name: 'skdetail',
  initialState: { shopname: " ", },
  reducers: {
    updatename(state,action){
                state.shopname=action.payload.shopname;
                return shopname;
            }
  }
})

export const namesactions = names.actions;
export default names; 

index.js\商店:

import { configureStore, createSlice } from "@reduxjs/toolkit";
import names from "./display";

const store = configureStore({
  reducer: {
    name: names.reducer,
  },
});

export default store;

index.js\src:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import store from './store';
import {
  createBrowserRouter,
  RouterProvider,
} from "react-router-dom";
import { Provider } from 'react-redux';
import { BrowserRouter } from "react-router-dom";

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <BrowserRouter>
      <Provider store ={store}>
        <App />
      </Provider>
    </BrowserRouter>
  </React.StrictMode>
);

我收到的错误为

'shopname' is not defined  no-undef

display.js\store
下 - 所以不考虑在display.js中设置为initialState的商店名称?如何使其成为定义变量?当我在 redux 开发工具上检查它时,它显示状态为未定义:(

我尝试为 sksignup.jsx 设置单独的本地状态,然后在商店中更新它。它对我不起作用。我正处于起步阶段,正在努力学习...所以请帮助..

reactjs react-redux redux-toolkit
1个回答
1
投票

createSlice 生成的操作将返回一个合适的对象,其中包含用于调度函数的有效负载。因此,在这种情况下,您唯一应该提供的是具有 shopname 属性的对象。在您提供的示例中,有效负载的根目录中基本上缺少商店名称,这会导致未定义的错误。 所以你应该将 showdetails 函数更改为:

  const showdetails =(e) =>{
        setshopname(e)
        dispatch(
            namesactions.updatename({shopname})
        )
    }

另请参阅 docs

中的示例“setUserName”
© www.soinside.com 2019 - 2024. All rights reserved.