简体   繁体   English

状态未在 React Hooks 的使用效果中得到更新

[英]State Not getting Updated In Use Effect of React Hooks

This is the code I am using.这是我正在使用的代码。 Response is totally correct.回应完全正确。 But setState methods not updating the state and showing me the initial states that are "".但是 setState 方法不会更新状态并向我显示“”的初始状态。 What i am doing wrong?我在做什么错? I am using them but this occurred for the very first time.我正在使用它们,但这是第一次发生。

  • "React": "^16.2.0" “反应”:“^16.2.0”
  • "react-dom": "^16.2.0" “反应DOM”:“^ 16.2.0”
const [name, setName] = useState("");
const [gender, setGender] = useState("");
const [skillSet, setSkillSet] = useState([]);
const [dob, setDob] = useState("");
useEffect(() => {
    async function getStudent() {
        try {
            const { data } = await axios.get("/student/1");
            const student = data[0];
            const skills = data[1];
            console.log(student[0]);
            const { name: n, dob: d, gender: g } = student[0];
            setName(n);
            setGender(g);
            setDob(d);
            console.log("Logging Name", name);
            console.log(n);
            alert(name);
        } catch (error) {}
    }
    getStudent();
}, []);

EDIT编辑

Here is my complete component whose snippet i posted above.这是我在上面发布的完整组件的片段。 So can you guide me on this?所以你能指导我吗? Otherwise i have to return to class components否则我必须返回类组件

import React, { useState, useEffect } from "react";
import BaseInputComponent from "../Utils/InputComponentMaterialUi";
import BaseSelect from "../Utils/SelectComponentMaterialUi";
import instruments from "../InstrumentNames";
import BaseCheckBox from "../Utils/CheckBoxMaterialUi";
import axios from "axios";


const StudentProfile = () => {
    const [name, setName] = useState("");
    const [gender, setGender] = useState("");
    const [skillSet, setSkillSet] = useState([]);
    const [dob, setDob] = useState("");
    useEffect(() => {
        async function getStudent() {
            try {
                const { data } = await axios.get("/student/1");
                const student = data[0];
                const skills = data[1];
                console.log(student[0]);
                const { name: n, dob: d, gender: g } = student[0];
                setName(n);
                setGender(g);
                setDob(d);
                console.log("Logging Name", name);
                console.log(n);
                alert(name);
            } catch (error) {
                console.log(error);
                console.log("Hi");
            }
        }
        getStudent();
    }, []);
    return (
        <div className="container" style={{ marginTop: "5rem" }}>
            <form>
                <div className="row">
                    <div className="col-md-6 col-12 col-lg-6">
                        <BaseInputComponent
                            value={name}
                            changeHandler={setName}
                            label={"Musician's Name"}
                        />
                    </div>
                    <div className="col-md-6 col-12 col-lg-6">
                        <BaseInputComponent
                            changeHandler={setDob}
                            value={dob}
                            type="date"
                            label={"Date Of Birth"}
                            InputLabelProps={{
                                shrink: true
                            }}
                        />
                    </div>
                    <div className="col-md-6 col-12 col-lg-6">
                        <BaseSelect
                            label={"Choose Gender"}
                            value={gender || ""}
                            changeHandler={setGender}
                            options={[
                                { label: "Male", value: "Male" },
                                { label: "Female", value: "Female" },
                                { label: "Other", value: "Other" }
                            ]}
                        />
                    </div>
                    <div className="col-md-6 col-12 col-lg-6">
                        <BaseInputComponent label={"Osama Inayat"} />
                    </div>
                </div>
                <button type="submit" className="btn submit-button">
                    Update Profile Infomation
                </button>
                <br />
                <br />
                <br />
            </form>
            <div style={{ width: "100%", height: "2px", background: "gray" }}>
                <h2 className="text-center">Select Instruments You Played</h2>
                <form>
                    <div className="row">
                        {instruments.map((name, i) => (
                            <div className="col-md-3 col-6">
                                <BaseCheckBox
                                    skillSet={skillSet}
                                    setSkillSet={setSkillSet}
                                    key={i}
                                    label={name}
                                    value={i}
                                />
                            </div>
                        ))}
                    </div>
                </form>
            </div>
            <button onClick={() => console.log(skillSet)}>Show Object</button>
        </div>
    );
};

export default StudentProfile;

To expand upon my comment – a minimized example with the same idea (without async , since the version of Babel on Stack Overflow doesn't support it, sigh) works fine, so the issue is likely in the components you use within StudentProfile , not in your hooks:扩展我的评论 - 一个具有相同想法的最小化示例(没有async ,因为 Stack Overflow 上的 Babel 版本不支持它,叹气)工作正常,所以问题可能出在您在StudentProfile使用的组件中,而不是在你的钩子里:

 function pretendAxios() { return Promise.resolve({ data: [[{ name: "foo", dob: "1234-1234", gender: "bar" }], ["skill"]] }); } const StudentProfile = () => { const [name, setName] = React.useState(""); const [gender, setGender] = React.useState(""); const [skillSet, setSkillSet] = React.useState([]); const [dob, setDob] = React.useState(""); React.useEffect(() => { pretendAxios().then(({ data }) => { const student = data[0]; const skills = data[1]; const { name: n, dob: d, gender: g } = student[0]; setName(n); setGender(g); setDob(d); }); }, []); return <div>{JSON.stringify({ name, gender, skillSet, dob })}</div>; }; ReactDOM.render(<StudentProfile />, document.getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script> <div id="root"></div>

    <TextField
        onChange={e => changeHandler(e.target.value)}
        id="standard-required"
        label={label}
        defaultValue={value}
        className={classes.textField}
        margin="normal"
        name={name}
        id={id}
        style={{ width: "100%" }}
        {...rest}
    />

The above code i had written in me BaseInput component after changing defaultValue to value my problem solved thanks to @AKX for pointing out the problem以上代码是我在将defaultValue更改为value后在BaseInput组件中编写的,由于@AKX 指出了问题,我的问题解决了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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