How to use useState to update Data?

霸气de小男生 提交于 2021-02-11 12:23:04

问题


I am building a multistep Form and I am trying to update my Data with the useState-Hook.

Unfortunatly I do no how to pass the components of the hook as a prop, to update them, after performing an onClick Event

Thats the important part of my code

multisteform.js

const defualtData = {
    Grundstück:'',
    Haus:"Haus",
    Wohnung:"Wohnung",
    Gewerbe:"Gewerbe",


}

const steps = [
    {id: 'Häuser'},
    {id: 'Fläche'},
    {id: 'Grundstückerschlosse'},
    {id: 'Bebauungsmöglichkeiten'}
]





export const  MultiStepFrom = () => {

const [formData, setForm] = useState(defualtData)
    const {step, navigation} = useStep({
        steps, 
        initialStep: 0,
    })
    
    const props = {formData, setForm, navigation}

    switch(step.id) {
    case 'Häuser':
        return <Häuser {...props} />
     
     case 'Fläche':
         return <Fläche {...props} />   
}



   
}

export default MultiStepFrom

Häuser.js

    function Häuser({ formData, setForm, navigation }) {


   const { Grundstück, Haus, Wohnung, Gewerbe } = formData;

    const changState = () => {
        navigation.next();

       // setForm([{ Grundstück: 'Grund', Haus:'Hauss' }]);
        //Here is my problem
       setForm(...formData, {
           Grundstück: "G",
       })

    }

<div
       className="container__containerimgage"
         name="Grundstück"
          value={Grundstück}
         onClick={changState}
                                    
 >

Thats the next page (but the data is not reaching that component, if I console .log (formData) I am just getting an emtpy array Also I can not target the data of the array

function Fläche({formData, setForm, navigation}) {

console.log(formData)

    console.log(Grundstück, Haus, Wohnung)

回答1:


Use setForm like below.

setForm({ ...formData, Grundstück: 'G' });


来源:https://stackoverflow.com/questions/65858221/how-to-use-usestate-to-update-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!