我正在为页面布局创建一个调查问卷表格,该页面布局包含可重复使用的React组件,状态来self 的Reduxstore .我的状态已更新,但更新的状态在页面上未正确呈现.特别是在复习路由上,我的item.value个不见了.如何获取要渲染的值?

App.jsx

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './App.css';
import { useDispatch, useSelector } from 'react-redux';
import { Route, useHistory } from 'react-router-dom';

function App() {
  const history = useHistory();
  const dispatch = useDispatch();
  const feedbackSchema = useSelector((store) => store.feedbackSchema);
  const [inputValue, setInputValue] = useState('');

  useEffect(() => {
    fetchFeedback();
  }, []);

  const fetchFeedback = () => {
    axios({
      method: 'GET',
      url: 'api/feedback',
    })
      .then((response) => {
        dispatch({
          type: 'SET_FEEDBACK',
          payload: response.data,
        });
      })
      .catch((error) => {
        console.log('You had a axios GET error', error);
      });
  };

  const handleSubmit = (item, index) => {
    console.log(item, inputValue);
    dispatch({
      type: 'SET_VALUE',
      payload: [item, inputValue],
    });
    history.push(
      feedbackSchema[index + 1]?.route
        ? `/${feedbackSchema[index + 1]?.route}`
        : '/review'
    );
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1 className="App-title">Feedback!</h1>
        <h4>Don't forget it!</h4>
      </header>
      {feedbackSchema.map((item, index) => {
        return (
          <div key={item.key} className="feedback-container">
            <Route exact path={`/${item.route}`}>
              <h1>{item.header}</h1>
              <form>
                <div className="feedback-input">
                  <p className="feedback-topic">{item.topic}</p>
                  <input
                    type="text"
                    value={inputValue}
                    onChange={(event) => setInputValue(event.target.value)}
                  />
                  <br />
                  <button
                    type="button"
                    onClick={() => handleSubmit(item.key, index)}
                  >
                    Next
                  </button>
                </div>
              </form>
            </Route>
          </div>
        );
      })}
      <Route exact path={`/review`}>
        <h1>Review Your Feedback</h1>
        {feedbackSchema.map((feedback) => {
          return (
            <p key={feedback.key}>
              {JSON.stringify(feedback)}
              {feedback.key}: {feedback.value}
            </p>
          );
        })}
      </Route>
    </div>
  );
}

export default App;

Store.js

import { applyMiddleware, combineReducers, createStore } from "redux";
import logger from "redux-logger";

const feedbackList = (state = [], action) => {
    if (action.type === 'SET_FEEDBACK') {
        return action.payload;
    }
    return state;
}

const feedbackSchema = (state = [
    { key: "feeling", route: "", header: "How are you feeling today?", topic: "Feeling?", value: "" },
    { key: "understanding", route: "understanding", header: "How well are you understanding the content?", topic: "Understanding?", value: "" },
    { key: "support", route: "support", header: "How well are you being supported?", topic: "Support?", value: "" },
    { key: "comments", route: "comments", header: "Any comments you want to leave?", topic: "Comments", value: "" }

], action) => {
    if (action.type === 'SET_VALUE') {
        state.map((feedback) => {
            if (feedback.key === action.payload[0]) {
                feedback.value = action.payload[1]
            }
            return feedback;
        })
    }
    return state;
}

const store = createStore(
    combineReducers({
        feedbackList,
        feedbackSchema,
    }),
    applyMiddleware(logger)
)

export default store;

index.jsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './components/App/App';
import { Provider } from 'react-redux';
import { HashRouter as Router } from 'react-router-dom';
import store from './store';

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

UI not rendering state/data

推荐答案

状态已更新,但UI未更新,因为react-redux通过比较数据地址来判断数据是否更改.

在您的Store.js文件中

const feedbackSchema = (state = [], action) => {
    if (action.type === 'SET_VALUE') {
        state.map((feedback) => {
            if (feedback.key === action.payload[0]) {
                feedback.value = action.payload[1]
            }
            return feedback;
        })
    }
    return state;
}

您通过更新状态返回相同的数据.因此,简化器会比较状态地址是否等于状态地址.这使得它认为没有做出任何改变.

相反,你可以这样做,

const feedbackSchema = (state = [], action) => {
    if (action.type === 'SET_VALUE') {
       const temp = state.map((feedback) => {
            if (feedback.key === action.payload[0]) {
                feedback.value = action.payload[1]
            }
            return feedback;
        })
    }
    return temp;
}

通过返回新变量temp reducer将了解所做的更改并更新UI.

Javascript相关问答推荐

如何将元素排列得彼此靠近?

在JavaScript中使用setProperty方法试图修改css元素值时,我遇到错误

如何计算数组子级的深度- Vue.js

TestCafe预计文本等于以下内容之一

Python类实现的JavaScript吊坠是什么样子的?

如何在dataTables PDF输出中正确渲染字形?

积分计算和 colored颜色 判断错误

Cypress -使用commands.js将数据测试id串在一起失败,但在将它们串在一起时不使用命令有效

使用axios.获取实时服务器时的404响应

togglePopover()不打开但不关闭原生HTML popover'

如何让npx在windows中运行js脚本?

无法从NextJS组件传递函数作为参数'

并不是所有的iframe都被更换

JavaScript不重定向配置的PATH

Vaadin定制组件-保持对javascrip变量的访问

当标题被点击时,如何使内容出现在另一个div上?

对具有相似属性的对象数组进行分组,并使用串连的值获得结果

Jexl to LowerCase()和Replace()

自动滚动功能在当前图像左侧显示上一张图像的一部分

react 路由DOM有条件地呈现元素