无法在反应上下文 api 中更新状态

时间:2020-12-26 16:05:05

标签: javascript reactjs

这是我的背景。我通过包装 .所以这不是问题。虽然我无法更新所有应用程序中的状态,但我只能通过该组件更新状态。

import React, { createContext, useState } from "react";
export const DoctorRequestContext = createContext();

export const DoctorRequestProvider = (props) => {
  const [doctorRequest, setDoctorRequest] = useState({
    name: "",
    surname: "",
    age: "",
    nationality: "",
    email: "",
    phone: "",
    message: "",
    address: "",
    timeChecked: "",
    timeStart: "",
    timeStamp: "",
    language: [],
    modalShow: false,
    doctorChatId: "",
    doctorChatName: "",
    showChat: false,
    chatMessages: [],
    hourOfVisit: "",
    dateOfVisit: "",
    key: "home",
  });

  return (
    <DoctorRequestContext.Provider value={[doctorRequest, setDoctorRequest]}>
      {props.children}
    </DoctorRequestContext.Provider>
  );
};


我制作了当前状态的副本,并在更新之后。但它不起作用

const handleMessageDoctor = () => {
    let newState = Object.assign({}, doctorRequest);
    newState.doctorChatId = props.doctorId;
    newState.doctorChatName = props.doctorName;
    newState.showChat = true;

    // ERRORE NON CAMBIA LO STATOOO
    console.log("new copy created", newState);
    setDoctorRequest(newState);
    console.log("after set state", doctorRequest);

    props.changeTab("chat");
  };

2 个答案:

答案 0 :(得分:0)

我可能会说问题在于调用值时的 []。

相反,请尝试:

value={{ doctorRequest, setDoctorRequest }}

注意:需要使用上下文(useContext),重构语句变量及其功能

答案 1 :(得分:0)

您将错误的对象作为 value 传递给上下文提供程序。使用 {} 而不是 []

import React, { createContext, useState } from 'react';
export const DoctorRequestContext = createContext();

export const DoctorRequestProvider = props => {
  const [doctorRequest, setDoctorRequest] = useState({
    name: '',
    surname: '',
    age: '',
    nationality: '',
    email: '',
    phone: '',
    message: '',
    address: '',
    timeChecked: '',
    timeStart: '',
    timeStamp: '',
    language: [],
    modalShow: false,
    doctorChatId: '',
    doctorChatName: '',
    showChat: false,
    chatMessages: [],
    hourOfVisit: '',
    dateOfVisit: '',
    key: 'home'
  });

  const value = {
    doctorRequest,
    setDoctorRequest
  };

  return (
    <DoctorRequestContext.Provider value={value}>
      {props.children}
    </DoctorRequestContext.Provider>
  );
};

一切正常,但是在使用日志检查值时会出现问题。检查下面的注释行。

const { doctorRequest, setDoctorRequest } = useContext(DoctorRequestContext);

const handleMessageDoctor = () => {
  let newState = Object.assign({}, doctorRequest);
  newState.doctorChatId = props.doctorId;
  newState.doctorChatName = props.doctorName;
  newState.showChat = true;

  // ERRORE NON CAMBIA LO STATOOO
  console.log('new copy created', newState);
  setDoctorRequest(newState);
  console.log('after set state', doctorRequest); // at this point you will not see changed doctorRequest because setDoctorRequest is async function.

  props.changeTab('chat');
};