简体   繁体   中英

Why won't my array of JSX elements appear in my reactjs render?

I am building a small trivia app and am trying to insert an updated array of "Choice" elements for each question, however when I try to insert an array of JSX elements, the array continually shows up as blank and I have no idea why:

let choices = [];

const generateChoices = (answers) => {

        for(let i = 0; i < answers.length; i++){
            choices.push(<ChoiceButton key={answers[i]} value={answers[i]} clicked={(answer) => setSelectedAnswer(decodeURIComponent(answer))}>{answers[i]}</ChoiceButton>);
        };

    };

generateChoices(["One", "Two", "Three", "Four"]);

<BoxWrapper>
...
<Fragment>
     <ChoiceForm>
     {choices}
     <SubmitButton isDisabled={!selectedAnswer} clicked={(e) => {e.preventDefault(); checkAnswer();}}>Submit</SubmitButton>
     </ChoiceForm>
</Fragment>
...
</BoxWrapper>

From ChoiceButton.js:

const ChoiceButton = props => {

    return (<Fragment>
                <ChoiceRadio type="radio" id={props.value} name="choice" onClick={() => props.clicked(props.value)}/>
                <ChoiceLabel htmlFor={props.value} correct={props.correct}>{props.children}</ChoiceLabel>
            </Fragment>
    )
}

From what I can tell, if I do console.log(choices) , it indicates that I have 4 JSX elements in there, but the array shows up blank in the React Debugger. How could I fix this?

I think you need to loop through the array. try doing

{choices.map(choice=>choice)}

something like that. Basically, you should render them one by one by looping through the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM