状态未更新React挂钩的使用效果

时间:2020-02-03 17:09:59

标签: reactjs

这是我正在使用的代码。回应是完全正确的。但是setState方法不会更新状态并向我显示初始状态为“”。我做错了什么?我正在使用它们,但这是第一次发生。

  • “反应”:“ ^ 16.2.0”
  • “ react-dom”:“ ^ 16.2.0”
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;

编辑

这是我完整的组件,上面是我发布的摘录。那你可以指导我吗?否则,我必须返回类组件

{{1}}

2 个答案:

答案 0 :(得分:1)

根据我的评论进行扩展–一个具有相同想法的最小化示例(没有async,因为堆栈溢出的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>

答案 1 :(得分:0)

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

在将BaseInput更改为defaultValue之后,我在value组件中编写了以上代码,由于@AKX指出了问题,我的问题得以解决