Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

reactjs - set hook with temporary object

i expect the hook to be updated(and i want every time to keep only one object i dont want to save previous value) my hooks:

  const [rooms, setrooms] = useState([]);
  const [roomFilter,setRoomFilter]=useState([])

function to update roomFilter hook:

  const deleteR=(i)=>{
      var temp=rooms.filter((element,index)=>(index==i))
    setRoomFilter([temp[0].Name])

somehow it shows nothing in roomFilter hook after update i have tried also initiakize my hook like this:

  const [roomFilter,setRoomFilter]=useState({})

i dont understand why

edit i am using function deleteR like this:

<Route exact path="/"component={() => { return <HomeScreen rooms={rooms} filter={deleteR} room={roomFilter} /> }}

from HomeScreen component i have two more components : HomeScreenRooms and Room function roomFilter is been sent from app to HomeSCreen >to HomeScreenRooms

HomeScreen:

<HomeScreenRooms rooms={props.rooms}  filter={props.filter} room={props.roomFilter} />

HomeScreenRooms:

 {props.rooms.map((element) => {
            return ( <div style={{ width: "100px",height: "100px",position: "relative",
             left: "-150px",top: "-100px",display: "inline" }}>

                <Link to="/room"><button onClick={() => {props.filter(element.index) }}  style={{ width: "116px",height: "116px",backgroundColor: element.color,position: "relative",fontWeight: "bold", color: "white",fontSize: "18px", border: "3px solid rgb(84,84,84)" }}>
                    <p>
                      <span>{element.room} </span>
                    </p>
                    
                    <p>
                      <span
                        style={{ fontWeight: "bold", color: "rgb(84,84,84)" }}>{element.Name}  
                         </span>
                    </p>

                  </button>
                 
                </Link>
question from:https://stackoverflow.com/questions/65857887/set-hook-with-temporary-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try this

const deleteR = (i) => {
  setRoomFilter((prevState) => {
    var temp = prevState.filter((element, index) => index == i); //consider using a unique id
    return [temp[0].Name];
  });
};

note: I would recommend you use some sort of unique identification to remove from a list, and not an index.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...