Javascript 我的状态没有使用React钩子更新

Javascript 我的状态没有使用React钩子更新,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我有一个事件会在发生变化时触发。此事件检查已更改的筛选器,然后相应地更新状态 如果我没有使用react钩子,我会选择这样的东西- const target = e.target; const value = e.type === "checkbox" ? target.checked : target.value; const name = e.target.name; this.setState({ [name]: value }); 如您所见,我可以使用[nam

我有一个事件会在发生变化时触发。此事件检查已更改的筛选器,然后相应地更新状态

如果我没有使用react钩子,我会选择这样的东西-

const target = e.target;
const value = e.type === "checkbox" ? target.checked : target.value;
const name = e.target.name;    
this.setState({ [name]: value });
如您所见,我可以使用
[name]
更新州名,但由于我使用的是react钩子,因此无法使用上述选项。相反,我得到了这个-

  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;
    }
  };
由于某些原因,您上面看到的内容不起作用。当我触发过滤器时,它进入案例,因为我已经测试过了,但是状态似乎没有更新。名称和值也被记录下来了,它们也很好。我不知道是什么原因导致了这一点,我只是新的编程,所以任何帮助将不胜感激


***只是重申一下,值和名称都有效,switch语句也有效。只是状态没有更新***

您导入useState了吗

import React, {useState} from 'react';

欢迎来到SO。您仍然可以为useState提供的
这个.setState
示例编写类似的代码。下面是一个快速运行的示例

一个围绕您的项目的答案:

  • 创建一个使用useContext的组件,只需加载所需的值和handleChange方法
  • constrootel=document.getElementById('root');
    常量应用=()=>{
    const[form,setForm]=React.useState({
    名称:“”,
    复选框:false,
    });
    常数handleChange=(e)=>{
    const target=e.target;
    const value=e.type==“checkbox”?target.checked:target.value;
    const name=e.target.name;
    setForm(prevState=>({…prevState,[名称]:值}));
    }
    返回(
    名称
    复选框
    {JSON.stringify(form)}
    )
    }
    ReactDOM.render(,rootEl)
    
    解决我的问题的办法是,它没有重新渲染,因此它比整个时间晚了一个周期

    在useEffect中将状态添加为依赖项可以解决问题!我希望这能帮助其他有类似问题的人,能以这样或那样的方式帮助社区

    import React,{createContext,useState,useffect}来自“React”;
    从“./数据”导入项目;
    export const RoomContext=createContext();
    const RoomProvider=(道具)=>{
    常数[房间,设置房间]=useState([]);
    常量[sortedRooms,setSortedRooms]=useState([]);
    常量[featuredRooms,setFeaturedRooms]=useState([]);
    const[loading,setLoading]=useState(true);
    const[type,setType]=useState(“全部”);
    const[容量,设置容量]=使用状态(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[早餐,setBreakfast]=使用状态(false);
    const[pets,setPets]=使用状态(false);
    //调用格式化数据
    useffect(()=>{
    //固定房间
    const rooms=格式数据(项目);
    //设置特色房间
    const featuredRooms=rooms.filter((room)=>room.featured==true);
    //始终将最高价格显示为默认值
    const maxPrice=Math.max(…rooms.map((item)=>item.price));
    //始终将最高价格显示为默认值
    const maxSize=Math.max(…rooms.map((item)=>item.size));
    休息室;
    设置房间(房间);
    setFeaturedRooms(特征Drooms);
    设置加载(假);
    设置最高价格(最高价格);
    setMaxSize(maxSize);
    设定价格(最高价格);
    }, [
    类型,
    容量,
    价格,
    明普莱斯,
    maxPrice,
    minSize,
    最大尺寸,
    早餐,
    宠物,
    ]);
    //格式化数据是从原始数据中获取我们想要提取的所有必需字段
    常量格式数据=(项)=>{
    让tempItems=items.map((item)=>{
    const id=item.sys.id;
    const images=item.fields.images.map((image)=>image.fields.file.url);
    constroom={…item.fields,images:images,id:id};
    返回室;
    });
    归还物品;
    };
    const getRoom=(slug)=>{
    让临时房间=[…房间];
    constroom=tempRooms.find((room)=>room.slug===slug);
    返回室;
    };
    常数handleChange=(e)=>{
    const target=e.target;
    const value=e.type==“checkbox”?target.checked:target.value;
    const name=e.target.name;
    交换机(名称){
    案例“类型”:
    设置类型(值);
    打破
    案例“能力”:
    设定容量(值);
    打破
    案例“价格”:
    设定价格(价值);
    打破
    案例“minPrice”:
    设定价格(价值);
    打破
    案例“maxPrice”:
    setMaxPrice(值);
    打破
    案例“minSize”:
    setMinSize(值);
    打破
    案例“maxSize”:
    setMaxSize(值);
    打破
    案例“早餐”:
    setBreakfast(值);
    打破
    案例“宠物”:
    setPets(值);
    打破
    违约:
    返回;
    }
    console.log(名称、值);
    };
    常量筛选器内存=()=>{
    让initialRooms=[…房间];
    如果(类型!=“全部”){
    initialRooms=initialRooms.filter((房间)=>room.type===type);
    }
    控制台日志(“房间类型为”,类型);
    设置房间(初始房间);
    };
    返回(
    {props.children}
    );
    };
    导出默认RoomProvider;
    
    您可以粘贴完整的代码还是显示问题的代码沙盒小项目?您如何验证/验证未更新的状态?您可以粘贴完整的代码,并让我们知道您如何验证是否更新状态。我已经记录了它,但因为我知道它不是即时的,所以我还设置了超时来检查状态几秒钟后。这是完整的代码文件:。。。在第105行,在进行更新时,必须使用生命周期方法记录状态,即对于基于类的组件,
    componentdiddupdate
    ,对于功能组件,
    useffect
    。您还可以使用react-dev-t
    const Test = () => {
      const { type, capacity, handleChange } = React.useContext(RoomContext);
    
      console.log(type, capacity);
    
      return (
          <div>
            <select name="type" onChange={handleChange}>
                <option value="all">all</option>
                <option value="another">another</option>
                <option value="one">one</option>
            </select>
            <select name="capacity" onChange={handleChange}>
              <option value="1">1</option>
              <option value="50">50</option>
              <option value="100">100</option>
            </select>
          </div>
      )
    };
    
    const target = e.target;
    const value = e.type === "checkbox" ? target.checked : target.value;
    const name = e.target.name;    
    this.setState({ [name]: value });
    
    import React, { createContext, useState, useEffect } from "react";
    
    import items from "../data";
    
    export const RoomContext = createContext();
    
    const RoomProvider = (props) => {
      const [rooms, setRooms] = useState([]);
      const [sortedRooms, setSortedRooms] = useState([]);
      const [featuredRooms, setFeaturedRooms] = useState([]);
      const [loading, setLoading] = useState(true);
      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 [breakfast, setBreakfast] = useState(false);
      const [pets, setPets] = useState(false);
    
      //call the formatted data
      useEffect(() => {
        //set rooms
        const rooms = formatData(items);
        //set the featured rooms
        const featuredRooms = rooms.filter((room) => room.featured === true);
        //always show the max price as default
        const maxPrice = Math.max(...rooms.map((item) => item.price));
        //always show the max price as default
        const maxSize = Math.max(...rooms.map((item) => item.size));
    
        setRooms(rooms);
        setSortedRooms(rooms);
        setFeaturedRooms(featuredRooms);
        setLoading(false);
        setMaxPrice(maxPrice);
        setMaxSize(maxSize);
        setPrice(maxPrice);
      }, [
        type,
        capacity,
        price,
        minPrice,
        maxPrice,
        minSize,
        maxSize,
        breakfast,
        pets,
      ]);
    
      //format data is getting all the required fields we want to pull from the originl data
      const formatData = (items) => {
        let tempItems = items.map((item) => {
          const id = item.sys.id;
          const images = item.fields.images.map((image) => image.fields.file.url);
    
          const room = { ...item.fields, images: images, id: id };
          return room;
        });
        return tempItems;
      };
    
      const getRoom = (slug) => {
        let tempRooms = [...rooms];
        const room = tempRooms.find((room) => room.slug === slug);
        return room;
      };
    
      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;
          case "breakfast":
            setBreakfast(value);
            break;
          case "pets":
            setPets(value);
            break;
          default:
            return;
        }
        console.log(name, value);
      };
    
      const filteredRooms = () => {
        let initialRooms = [...rooms];
    
        if (type !== "all") {
          initialRooms = initialRooms.filter((room) => room.type === type);
        }
        console.log("room type is", type);
        setSortedRooms(initialRooms);
      };
    
      return (
        <RoomContext.Provider
          value={{
            rooms,
            featuredRooms,
            getRoom,
            loading,
            sortedRooms,
            type,
            capacity,
            price,
            minPrice,
            maxPrice,
            minSize,
            maxSize,
            breakfast,
            pets,
            handleChange,
            filteredRooms,
          }}
        >
          {props.children}
        </RoomContext.Provider>
      );
    };
    
    export default RoomProvider;