【问题标题】:How to make states from the keys of state object in react?如何从状态对象的键中做出状态反应?
【发布时间】:2020-10-15 13:51:34
【问题描述】:

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

这是我的代码:

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>
      )
    }

【问题讨论】:

    标签: node.js reactjs socket.io


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2020-07-26
      • 2018-08-12
      • 1970-01-01
      • 2021-06-22
      • 2019-10-27
      • 2021-06-06
      相关资源
      最近更新 更多