You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Store中'shopname'未定义错误及状态存储问题求助

解决Redux中shopname未定义及状态undefined问题

问题说明

在将注册表单的店铺名称(shopname)存入Redux Store时,出现'shopname' is not defined错误(位于store/display.js),且Redux DevTools显示该状态为undefined,即使组件内设置了本地state也无法正常同步到Store。

错误原因及修复步骤

1. 修复Reducer中的返回值错误

store/display.js的updatename reducer中,错误返回了未定义的shopname变量,正确做法是依赖Redux Toolkit的Immer自动处理不可变更新,无需手动返回未定义变量。

修改后的store/display.js:

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

const names = createSlice({
  name: 'skdetail',
  initialState: { shopname: "" },
  reducers: {
    updatename(state, action) {
      state.shopname = action.payload.shopname;
      // Immer会自动处理状态更新,无需手动return
    }
  }
})

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

2. 移除Dispatch中的手动type指定

Redux Toolkit的createSlice会自动为生成的action创建唯一type,无需在dispatch时手动指定type: "namesactions",同时直接传入当前输入值可避免本地state更新延迟问题。

修改sksignup.js中的showdetails函数:

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

3. 正确初始化useNavigate钩子

组件中未初始化navigate变量,需添加const navigate = useNavigate();以正常使用路由跳转功能。

4. 完善组件的JSX结构

组件的JSX代码必须包裹在return语句中,同时修复input标签的闭合问题。

修改后的完整sksignup.js:

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

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

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

  const insertdata = () => {
    axios.post('http://localhost:3001/register', { shopname })
      .then(() => {
        navigate('/userentry');
      })
      .catch(err => console.error('注册失败:', err));
  }

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

export default Sksignup;

其他说明

  • store/index.js和src/index.js的配置无需修改,已符合Redux集成要求。
  • 建议在axios请求中添加catch块,便于排查注册失败的问题。

内容的提问来源于stack exchange,提问作者DHARSHINI S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:23:15