如何通过状态对象的键使状态做出反应?

时间:2020-10-15 13:51:34

标签: node.js reactjs socket.io

因此,我试图从父组件状态在子组件中实现状态,正如您在代码中看到的那样。但是它给我未定义为子componenet中的状态值。要测试,可以conosle.log(questions)和您会看到未定义的内容。
是否有某种机制可以以某种方式在父组件中设置setState,以便子组件中的后续道具能够获取状态值?

这是我的代码:

import React, { useEffect, useState } from "react";
    import io from "socket.io-client";
    const ENDPOINT = "http://localhost:5000";
    let socket = io(ENDPOINT);
    
    export default function Screen() {
    
      const [qValue, setQuestion] = useState({personalInfo:{},questions:[]});
      const [aValue, setAnswer] = useState({personalInfo:{},answer:""});
    
      useEffect(() => {
        socket.on("screenAns", (input) => {
          setAnswer(JSON.parse(input));
        });
        console.log(aValue);
      }, [aValue]);
    
      useEffect(() => {
        socket.on("screenQs", (arrayValue) => {
          setQuestion(JSON.parse(arrayValue));
        });
        console.log((qValue));
      }, [qValue]);
    
      return (
        <div>
          <h2>Screen</h2>
          <QuestionSingleMode value={qValue} /> 
        </div>
      );
    }
    function QuestionSingleMode(props){
     
      var [questions,setQuestions]=useState(props.value.questions);
      var [renderQuestion,setRenderQuestion]=useState("")
      var [counter,setCounter]=useState(props.value.questions.length)
    
    useEffect(()=>{
     console.log(questions)
      setRenderQuestion(questions[0])
    },[renderQuestion])
      
      
     function nextQuestion(){
      setQuestions(questions.splice(0,1))
      setRenderQuestion(questions[0])
      setCounter(counter--)
    }
    
      return(
        <div>
          <h1>{renderQuestion}</h1>
          <button onClick={nextQuestion}>{counter ? "next" : "finish"}</button>
          
        </div>
      )
    }

1 个答案:

答案 0 :(得分:0)

实际上,我通过将 useEffect()数组中的 renderQuestion 更改为 props.questions 解决了该问题。