猿问

我的状态没有使用 React Hooks 更新

我有一个在更改时触发的事件。此事件检查哪个过滤器已更改,然后相应地更新状态。


如果我不使用反应钩子,我会去做这样的事情 -


const target = e.target;

const value = e.type === "checkbox" ? target.checked : target.value;

const name = e.target.name;    

this.setState({ [name]: value });

如您所见,我可以使用更新状态名称,[name]但由于我使用的是反应钩子,所以我无法使用上面的内容。相反,我得到了这个 -


  const [type, setType] = useState("all");

  const [capacity, setCapacity] = useState(1);

  const [price, setPrice] = useState(0);

  const [minPrice, setMinPrice] = useState(0);

  const [maxPrice, setMaxPrice] = useState(0);

  const [minSize, setMinSize] = useState(0);

  const [maxSize, setMaxSize] = useState(0);


  const handleChange = (e) => {

    const target = e.target;

    const value = e.type === "checkbox" ? target.checked : target.value;

    const name = e.target.name;

    

    switch (name) {

      case "type":

        setType(value);

        break;

      case "capacity":

        setCapacity(value);

        break;

      case "price":

        setPrice(value);

        break;

      case "minPrice":

        setMinPrice(value);

        break;

      case "maxPrice":

        setMaxPrice(value);

        break;

      case "minSize":

        setMinSize(value);

        break;

      case "maxSize":

        setMaxSize(value);

        break;

      default:

        return;

    }

  };

由于某种原因,您在上面看到的内容不起作用。当我触发过滤器时,它会进入案例,因为我已经对此进行了测试,但状态似乎没有更新。名称和值也已记录,它们也很好。我不确定是什么原因造成的,我只是编程的新手,所以任何帮助将不胜感激!


蝴蝶不菲
浏览 88回答 3
3回答

倚天杖

我的问题的解决方法是它没有重新渲染,所以它一直落后于整个时间。在 useEffect 中添加状态作为依赖项可以解决问题!我希望这可以帮助其他有类似问题的人,以某种方式帮助社区。import React, { createContext, useState, useEffect } from "react";import items from "../data";export const RoomContext = createContext();const RoomProvider = (props) => {&nbsp; const [rooms, setRooms] = useState([]);&nbsp; const [sortedRooms, setSortedRooms] = useState([]);&nbsp; const [featuredRooms, setFeaturedRooms] = useState([]);&nbsp; const [loading, setLoading] = useState(true);&nbsp; const [type, setType] = useState("all");&nbsp; const [capacity, setCapacity] = useState(1);&nbsp; const [price, setPrice] = useState(0);&nbsp; const [minPrice, setMinPrice] = useState(0);&nbsp; const [maxPrice, setMaxPrice] = useState(0);&nbsp; const [minSize, setMinSize] = useState(0);&nbsp; const [maxSize, setMaxSize] = useState(0);&nbsp; const [breakfast, setBreakfast] = useState(false);&nbsp; const [pets, setPets] = useState(false);&nbsp; //call the formatted data&nbsp; useEffect(() => {&nbsp; &nbsp; //set rooms&nbsp; &nbsp; const rooms = formatData(items);&nbsp; &nbsp; //set the featured rooms&nbsp; &nbsp; const featuredRooms = rooms.filter((room) => room.featured === true);&nbsp; &nbsp; //always show the max price as default&nbsp; &nbsp; const maxPrice = Math.max(...rooms.map((item) => item.price));&nbsp; &nbsp; //always show the max price as default&nbsp; &nbsp; const maxSize = Math.max(...rooms.map((item) => item.size));&nbsp; &nbsp; setRooms(rooms);&nbsp; &nbsp; setSortedRooms(rooms);&nbsp; &nbsp; setFeaturedRooms(featuredRooms);&nbsp; &nbsp; setLoading(false);&nbsp; &nbsp; setMaxPrice(maxPrice);&nbsp; &nbsp; setMaxSize(maxSize);&nbsp; &nbsp; setPrice(maxPrice);&nbsp; }, [&nbsp; &nbsp; type,&nbsp; &nbsp; capacity,&nbsp; &nbsp; price,&nbsp; &nbsp; minPrice,&nbsp; &nbsp; maxPrice,&nbsp; &nbsp; minSize,&nbsp; &nbsp; maxSize,&nbsp; &nbsp; breakfast,&nbsp; &nbsp; pets,&nbsp; ]);&nbsp; //format data is getting all the required fields we want to pull from the originl data&nbsp; const formatData = (items) => {&nbsp; &nbsp; let tempItems = items.map((item) => {&nbsp; &nbsp; &nbsp; const id = item.sys.id;&nbsp; &nbsp; &nbsp; const images = item.fields.images.map((image) => image.fields.file.url);&nbsp; &nbsp; &nbsp; const room = { ...item.fields, images: images, id: id };&nbsp; &nbsp; &nbsp; return room;&nbsp; &nbsp; });&nbsp; &nbsp; return tempItems;&nbsp; };&nbsp; const getRoom = (slug) => {&nbsp; &nbsp; let tempRooms = [...rooms];&nbsp; &nbsp; const room = tempRooms.find((room) => room.slug === slug);&nbsp; &nbsp; return room;&nbsp; };&nbsp; const handleChange = (e) => {&nbsp; &nbsp; const target = e.target;&nbsp; &nbsp; const value = e.type === "checkbox" ? target.checked : target.value;&nbsp; &nbsp; const name = e.target.name;&nbsp; &nbsp; switch (name) {&nbsp; &nbsp; &nbsp; case "type":&nbsp; &nbsp; &nbsp; &nbsp; setType(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; case "capacity":&nbsp; &nbsp; &nbsp; &nbsp; setCapacity(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; case "price":&nbsp; &nbsp; &nbsp; &nbsp; setPrice(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; case "minPrice":&nbsp; &nbsp; &nbsp; &nbsp; setMinPrice(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; case "maxPrice":&nbsp; &nbsp; &nbsp; &nbsp; setMaxPrice(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; case "minSize":&nbsp; &nbsp; &nbsp; &nbsp; setMinSize(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; case "maxSize":&nbsp; &nbsp; &nbsp; &nbsp; setMaxSize(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; case "breakfast":&nbsp; &nbsp; &nbsp; &nbsp; setBreakfast(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; case "pets":&nbsp; &nbsp; &nbsp; &nbsp; setPets(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; console.log(name, value);&nbsp; };&nbsp; const filteredRooms = () => {&nbsp; &nbsp; let initialRooms = [...rooms];&nbsp; &nbsp; if (type !== "all") {&nbsp; &nbsp; &nbsp; initialRooms = initialRooms.filter((room) => room.type === type);&nbsp; &nbsp; }&nbsp; &nbsp; console.log("room type is", type);&nbsp; &nbsp; setSortedRooms(initialRooms);&nbsp; };&nbsp; return (&nbsp; &nbsp; <RoomContext.Provider&nbsp; &nbsp; &nbsp; value={{&nbsp; &nbsp; &nbsp; &nbsp; rooms,&nbsp; &nbsp; &nbsp; &nbsp; featuredRooms,&nbsp; &nbsp; &nbsp; &nbsp; getRoom,&nbsp; &nbsp; &nbsp; &nbsp; loading,&nbsp; &nbsp; &nbsp; &nbsp; sortedRooms,&nbsp; &nbsp; &nbsp; &nbsp; type,&nbsp; &nbsp; &nbsp; &nbsp; capacity,&nbsp; &nbsp; &nbsp; &nbsp; price,&nbsp; &nbsp; &nbsp; &nbsp; minPrice,&nbsp; &nbsp; &nbsp; &nbsp; maxPrice,&nbsp; &nbsp; &nbsp; &nbsp; minSize,&nbsp; &nbsp; &nbsp; &nbsp; maxSize,&nbsp; &nbsp; &nbsp; &nbsp; breakfast,&nbsp; &nbsp; &nbsp; &nbsp; pets,&nbsp; &nbsp; &nbsp; &nbsp; handleChange,&nbsp; &nbsp; &nbsp; &nbsp; filteredRooms,&nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; {props.children}&nbsp; &nbsp; </RoomContext.Provider>&nbsp; );};export default RoomProvider;

桃花长相依

欢迎来到 SO。您仍然可以编写this.setState与 useState 提供的示例类似的代码。这是一个可快速运行的示例。围绕您的项目的答案:创建一个使用 useContext 的组件,只需加载您需要的值和 handleChange 方法const&nbsp;Test&nbsp;=&nbsp;()&nbsp;=>&nbsp;{&nbsp;&nbsp;const&nbsp;{&nbsp;type,&nbsp;capacity,&nbsp;handleChange&nbsp;}&nbsp;=&nbsp;React.useContext(RoomContext);&nbsp;&nbsp;console.log(type,&nbsp;capacity);&nbsp;&nbsp;return&nbsp;(&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select&nbsp;name="type"&nbsp;onChange={handleChange}> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<option&nbsp;value="all">all</option> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<option&nbsp;value="another">another</option> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<option&nbsp;value="one">one</option> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</select> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select&nbsp;name="capacity"&nbsp;onChange={handleChange}> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<option&nbsp;value="1">1</option> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<option&nbsp;value="50">50</option> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<option&nbsp;value="100">100</option> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</select> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div> &nbsp;&nbsp;) };添加 Test 组件作为 Room Provider 的子组件。启动应用程序,您应该会看到它会正常更新工作可运行示例:const target = e.target;const value = e.type === "checkbox" ? target.checked : target.value;const name = e.target.name;&nbsp; &nbsp;&nbsp;this.setState({ [name]: value });const rootEl = document.getElementById('root');const App = () => {&nbsp; const [form, setForm] = React.useState({&nbsp; &nbsp; name: '',&nbsp; &nbsp; checkbox: false,&nbsp; });&nbsp;&nbsp;&nbsp; const handleChange = (e) => {&nbsp; &nbsp; const target = e.target;&nbsp; &nbsp; const value = e.type === "checkbox" ? target.checked : target.value;&nbsp; &nbsp; const name = e.target.name;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; setForm(prevState => ({ ...prevState, [name]: value }));&nbsp; }&nbsp;&nbsp;&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <label>Name</label>&nbsp; &nbsp; &nbsp; <input type="text" name="name" value={form.name} onChange={handleChange} />&nbsp; &nbsp; &nbsp; <label>Checkbox</label>&nbsp; &nbsp; &nbsp; <input type="checkbox" name="checkbox" checked={form.checkbox} onChange={handleChange} />&nbsp; &nbsp; &nbsp; <pre>{JSON.stringify(form)}</pre>&nbsp; &nbsp; </div>&nbsp; )}ReactDOM.render(<App />, rootEl);<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script><div id="root"></div>这是具有多个 useState 的代码的运行示例。const rootEl = document.getElementById('root');const App = () => {&nbsp; const [name, setName] = React.useState('');&nbsp; const [checkbox, setCheckbox] = React.useState(false);&nbsp; const handleChange = (e) => {&nbsp; &nbsp; const target = e.target;&nbsp; &nbsp; const value = e.type === "checkbox" ? target.checked : target.value;&nbsp; &nbsp; const name = e.target.name;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; switch (name) {&nbsp; &nbsp; &nbsp; case "name":&nbsp; &nbsp; &nbsp; &nbsp; setName(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; case "checkbox":&nbsp; &nbsp; &nbsp; &nbsp; setCheckbox(value);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; };&nbsp;&nbsp;&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <label>Name</label>&nbsp; &nbsp; &nbsp; <input type="text" name="name" value={name} onChange={handleChange} />&nbsp; &nbsp; &nbsp; <label>Checkbox</label>&nbsp; &nbsp; &nbsp; <input type="checkbox" name="checkbox" checked={checkbox} onChange={handleChange} />&nbsp; &nbsp; &nbsp; <pre>{JSON.stringify({ name, checkbox })}</pre>&nbsp; &nbsp; </div>&nbsp; )}ReactDOM.render(<App />, rootEl);<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script><div id="root"></div>

函数式编程

你导入 useState 了吗?import&nbsp;React,&nbsp;{useState}&nbsp;from&nbsp;'react';
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答