如何显示更新的用户信息?

时间:2020-10-16 07:55:58

标签: reactjs

<-每当我尝试更新用户信息时,都不会获取更新的值。但是,当我重新加载页面时,我会获取更新的值。当我按下更新按钮时,是否有办法获取更新的值MiddlePanel中的哪个?现在,我正在loadUsers中获取所有用户。 ->

class Home extends Component {
          state = {
            loadUsers: [],
            currentUser: null,
          };
 

 async componentDidMount() {
        const res = await axios.get("http://localhost:5000/users");
        this.setState({ loadUsers: res.data });
      }

  setUser = (currentUser) => {
    this.setState({ currentUser });
  };

  render() {
    return (
      <Fragment>
        <div className="row">
          <div className="col-md-3" style={{ backgroundColor: "#303F9F" }}>
            <Typography variant="h6">List all Counsellors</Typography>
            {this.state.loadUsers.map((user) => {
              const { _id, firstname, lastname } = user;
              return (
                <div key={_id}>
                  <PrimaryButton
                    onClick={(e) => {
                      this.setUser(user);
                    }}
                  >
                    {firstname} {lastname}
                  </PrimaryButton>
                </div>
              );
            })}
          </div>
          <div className="col-md-2"></div>
          <div className="col-md-6">
            {this.state.currentUser && (
              <div>
                <MiddlePanel user={this.state.currentUser} />
              </div>
            )}
          </div> 
      </Fragment>
    );
  }
}

export default Home;
<--This is my MiddlePanel -->

const MiddlePanel = ({ user }) => {
  const [data, setData] = useState({
    firstname: "",
    lastname: "",
    email: "",
    phoneNo: "",
  });

  const { firstname, lastname, email, phoneNo } = data;

  useEffect(() => {
    const fetchUser = async () => {
      const res = await axios.get(`http://localhost:5000/users/${user._id}`);
      setData({
        firstname: res.data.firstname,
        lastname: res.data.lastname,
        email: res.data.email,
        phoneNo: res.data.phoneNo,
      });
    };
    fetchUser();
  }, [user._id]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setData({ ...data, [name]: value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const newUser = { firstname, lastname, email, phoneNo };
    try {
      const config = {
        headers: {
          "Content-Type": "application/json",
        },
      };
      const body = JSON.stringify(newUser);
      await axios.patch(
        `http://localhost:5000/users/${user._id}`,
        body,
        config
      );
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <div>
      <Form onSubmit={handleSubmit}>
        <Input
          type="text"
          name="firstname"
          onChange={handleChange}
          value={data.firstname}
        />
        <Input
          type="text"
          name="lastname"
          onChange={handleChange}
          value={data.lastname}
        />
        <Input
          type="email"
          name="email"
          onChange={handleChange}
          value={data.email}
        />
        <Input
          type="tel"
          name="phoneNo"
          onChange={handleChange}
          value={data.phoneNo}
        />
        <PrimaryButton>Update</PrimaryButton>
      </Form>
    </div>
  );
};

<-我想获取更新的用户->

2 个答案:

答案 0 :(得分:0)

似乎您应该在更新用户信息后重新获取数据

答案 1 :(得分:0)

我猜对对象键的值的更改永远不会反应...因此,请尝试将user.id设置为MiddlePanel中的状态变量

const [userId, setUserId] = useState(user.id)
...
useEffect(() => {
    ...
}, [userId])