반응 중인 다른 구성 요소로 상태를 해제하는 데 도움이 필요합니다.

8448 단어
저는 이미 백엔드에 성공적으로 게시하고 있는 다른 데이터와 함께 전송될 이 양식 데이터의 상태를 해제하는 데 정말 어려움을 겪었습니다. 사용자가 페이지 상단에 사용자 이름을 입력한 다음 해당 사용자 이름을 다른 데이터와 함께 백엔드로 보내도록 하려고 합니다. 구성 요소 내부에 있을 때 콘솔 로그 상태를 기록하려고 할 때 너무 해제하고 싶습니다. 콘솔에서 가장 오랫동안 '정의되지 않음'이 표시되었지만 지금은 내가 만든 양식 구성 요소의 일부가 상태를 콘솔에 기록하려고 할 때 콘솔. 이것은 상태를 기록하려고 할 때 콘솔에 표시되는 것입니다.

```"onLoad Flashcard.js:35 class NameForm extends react_WEBPACK_IMPORTED_MODULE_0_.Component { constructor(props) { super(props); this.handleChange = event => { this.setState({ value: event.target.value …

다음은 양식을 생성하는 NameForm.js 파일의 코드입니다.



import React from "react"
import CheckGuess from './Flashcard'


export default class NameForm extends React.Component {
    constructor(props) {
      super(props);
      this.state = {value: ''};   
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange = (event) => {
        this.setState({value: event.target.value});
    }

    handleSubmit = (event) => {  
        alert('A name was submitted: ' + this.state.value);
        this.props.CheckGuess(this.props.answer, this.state.value);
        event.preventDefault();
    }
    CheckGuess() {

    }

    render() {
      return (
          <div>
            <form onSubmit={this.handleSubmit}>
                <label>
                    Name:
                    <input type="text" value={this.state.value} onChange={this.handleChange} />
                </label>
                <input type="submit" value="Submit" />

            </form>
          </div>
      );
    }
}

and here is the code for my flashcard.js file which contains the CheckGuess function which sends  the  other data to the backend and is where i would like to send the username as well:




import React, { useState, useEffect, useRef } from 'react'
'./NameForm'에서 NameForm 가져오기
'./NameForm'에서 값 가져오기

export default function Flashcard({ flashcard }) {//flashcardlist.js의 매핑에서 각각 고유한 ID를 가진 flashcard prop을 수신합니다.

const MAX_TRIES = 4
// const [incorrect, setIncorrect] = useState(incorrect)
const [guess, setGuess] = useState(0)
const [flip, setFlip] = useState(false)
const [height, setHeight] = useState('initial') //sets the state for our initial height to be replaced by the max height

const frontEl = useRef() // lets us have a reference from the front and back through every rerendering of them
const backEl = useRef()

// const callDouble = () =>{
 //   checkGuess();
  //  postData();

//}

async function postData() {


}



const CheckGuess = (answer, stateValue) => {
    try {
        console.log(value)
        let result = fetch('http://127.0.0.1:5000/post', {
            method: 'POST',
            mode: 'no-cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',

            },
            body: JSON.stringify({
                key: `${Date.now()}`,
                question: flashcard.question,
                answer: flashcard.answer,
                options: flashcard.options,
                guess: answer,
                user: stateValue
            })
        });
    } catch(e) {
        console.log(e)
    }
    if (answer === flashcard.answer) {
        setFlip(true)
        return
    }
    if (guess + 1 === MAX_TRIES) {
        setFlip(true)
    }

    setGuess(guess + 1)
    // setIncorrect(true)
}

function setMaxHeight() {
    const frontHeight = frontEl.current.getBoundingClientRect().height //gives us dimensions of the rectangle but we only need the height
    const backHeight = backEl.current.getBoundingClientRect().height
    setHeight(Math.max(frontHeight, backHeight, 100)) // sets the height (setHeight) to the maximum height of front or back but the minimum is 100px
}

useEffect(setMaxHeight, [flashcard.question, flashcard.answer, flashcard.options]) //anytime any of these change then the setMaxHeight will change
useEffect(() => {
    window.addEventListener('resize', setMaxHeight) //everytime we resize our browser, it sets the max height again
    return () => window.removeEventListener('resize', setMaxHeight) //removes the eventlistener when component destroys itself
  }, [])

반품 (


    onClick={() =&gt; postData()}<br>
    className={<code>card ${flip ? 'flip' : ''}</code>} // if flip is true classname will be card and flip, if flip isnt true it will just be card<br>
    style={{ height: height }} //setting height to the variable height

    // onClick={() => setFlip(!flip)} // click changes it from flip to non flip
>
    <div className="front" ref={frontEl}>
        {flashcard.question}
        <div className='flashcard-options'>
            {flashcard.options.map(option => {
                return <div key={option} onClick={() => CheckGuess(option)} className='flashcard-option'>{option}</div>
            })}
        </div>
    </div> 
    <div onClick={() => setFlip(!flip)} className='back' ref={backEl}>
        {flashcard.answer}        
    </div>

</div>

)
}
//스타일을 지정할 클래스 이름이 있는 옵션을 각각 만들기 위해 옵션을 반복하여 질문과 답변을 표시하도록 전면 설정
//back은 답을 보여줍니다.

그런 다음 내 app.js 함수 내에서 NameForm을 렌더링하여 양식이 모든 플래시 카드 구성 요소 위에 잘 놓이도록 합니다.



import React, { useState, useEffect } from "react"
import FlashcardList from "./FlashcardList"
import './app.css'
import axios from 'axios' // makes importing from api easy
import NameForm from './NameForm'
import checkGuess from './Flashcard'
import flashcard from "./Flashcard"
import value from './NameForm'



export default function App() {
    const [flashcards, setFlashcards] = useState([])

    useEffect(() => {
        axios.get('http://127.0.0.1:5000/')
        .then(res => {
            setFlashcards(res.data.results.map((questionItem, index) => { // mapping over api to get objects "questionItem" and the index of each one
                const answer = decodeString(questionItem.correct_answer) // setting the correct_answer objects from api to answer
                const question = decodeString(questionItem.question)
                const options = [
                    ...questionItem.incorrect_answers.map(a => decodeString(a)), answer // spreading incorrect_answers objects into an array with answer at the back to set all of them into options
                ]
                return {
                    id: question, // sets the id to the index from the api and the exact time to make sure its always unique
                    question: question, // setting question objects from api to question
                    answer: answer, // already defined above
                    options: options.sort(() => Math.random() - .5), // sorting all the options randomly
                    user: value
                }
            }))
        })
    }, [])

    function decodeString(str) {
        const textArea = document.createElement('textarea')
        textArea.innerHTML= str
        return textArea.value // function brings all of our objects into this new element and decodes all of the encoded html
    }



    return (

           <div>
               <NameForm answer={flashcard.answer} checkGuess={checkGuess} />

                <div className="container">
                    <FlashcardList flashcards={flashcards} />
                </div>
            </div>
    )
}

 how can i get the actual state value inside that component? any help is greatly appreciated ive been trying to figure this out for a while and i have trouble with lifting state.










좋은 웹페이지 즐겨찾기