UseReducer dispatch 被调用两次

huangapple go评论60阅读模式
英文:

UseReducer dispatch getting called twice

问题

以下是您要的代码部分的翻译:

我有以下这段代码但是usereducer的dispatch方法被调用了两次我查阅了相关资料并从index中移除了strict模式现在方法被正确调用和运行但UI没有以更新后的值渲染出来有人可以帮忙吗

import React, { useReducer, useState } from "react";
import "../App.css";

const initialState = [
  { time: "17:00", slots: 3 },
  { time: "18:00", slots: 4 },
  { time: "19:00", slots: 2 },
  { time: "20:00", slots: 4 },
  { time: "21:00", slots: 3 },
  { time: "22:00", slots: 2 },
];

const reducer = (state, action) => {
  switch (action.type) {
    case "update": {
      let index = state.findIndex((x) => x.time === action.value);
      console.log(index);
      if (state[index].slots > 0) {
        state[index].slots -= 1;
      }
      console.log(state);
      return state;
    }
  }
};

function Reservations() {
  const [availableTimes, dispatch] = useReducer(reducer, initialState);

  const handleSubmit = (e) => {
    e.preventDefault();
    dispatch({ type: "update", value: time });
  };

  return (
    <>
      <label htmlFor="res-time">Choose time</label>
      <select
        id="res-time "
        value={time}
        onChange={(e) => setTime(e.target.value)}
      >
        {availableTimes.map((availableTime) => {
          return (
            <option key={availableTime.time} value={availableTime.time}>
              {availableTime.time} - {availableTime.slots} slots available
            </option>
          );
        })}
      </select>
    </>
  );
}

export default Reservations;

在我的index.js中,我已经移除了strictmode:

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  // <React.StrictMode>
  <BrowserRouter>
    <App />
  </BrowserRouter>
  // </React.StrictMode>
);
英文:

I have the following piece of code and the usereducer disptach method is getting called twice. I read up on this and removed the strict mode from index. Now the method is called and run properly but the UI is not getting rendered with the updated value. Can someone please help?

import React, { useReducer, useState } from &quot;react&quot;;
import &quot;../App.css&quot;;
const initialState = [
{ time: &quot;17:00&quot;, slots: 3 },
{ time: &quot;18:00&quot;, slots: 4 },
{ time: &quot;19:00&quot;, slots: 2 },
{ time: &quot;20:00&quot;, slots: 4 },
{ time: &quot;21:00&quot;, slots: 3 },
{ time: &quot;22:00&quot;, slots: 2 },
];
const reducer = (state, action) =&gt; {
switch (action.type) {
case &quot;update&quot;: {
let index = state.findIndex((x) =&gt; x.time === action.value);
console.log(index);
if (state[index].slots &gt; 0) {
state[index].slots -= 1;
}
console.log(state);
return state;
}
}
};
function Reservations() {
const [availableTimes, dispatch] = useReducer(reducer, initialState);
const handleSubmit = (e) =&gt; {
e.preventDefault();
dispatch({ type: &quot;update&quot;, value: time });
};
return (
&lt;&gt;
&lt;label htmlFor=&quot;res-time&quot;&gt;Choose time&lt;/label&gt;
&lt;select
id=&quot;res-time &quot;
value={time}
onChange={(e) =&gt; setTime(e.target.value)}
&gt;
{availableTimes.map((availableTime) =&gt; {
return (
&lt;option key={availableTime.time} value={availableTime.time}&gt;
{availableTime.time} - {availableTime.slots} slots available
&lt;/option&gt;
);
})}
&lt;/select&gt;
&lt;/&gt;
);
}
export default Reservations;

In my index.js, I have removed the strictmode

import React from &quot;react&quot;;
import ReactDOM from &quot;react-dom/client&quot;;
import &quot;./index.css&quot;;
import App from &quot;./App&quot;;
import reportWebVitals from &quot;./reportWebVitals&quot;;
import { BrowserRouter } from &quot;react-router-dom&quot;;
import &quot;bootstrap/dist/css/bootstrap.min.css&quot;;
const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));
root.render(
// &lt;React.StrictMode&gt;
&lt;BrowserRouter&gt;
&lt;App /&gt;
&lt;/BrowserRouter&gt;
// &lt;/React.StrictMode&gt;
);

答案1

得分: 1

React期望不可变的更新。不要直接通过赋值来更改状态;而是制作副本来表示下一个状态。

return state.map(x => x.time !== action.value ? x : 
                   {...x, slots: Math.max(0, x.slots - 1)});
英文:

React expects immutable updates. Do not directly change the state by assigning to it; instead make copies to represent the next state.

return state.map(x =&gt; x.time !== action.value ? x : 
                   {...x, slots: Math.max(0, x.slots - 1)});

huangapple
  • 本文由 发表于 2023年3月7日 11:38:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657844.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定