反应钩子useState消耗对象

时间:2020-07-01 22:37:03

标签: reactjs react-hooks use-state

我不确定如何正确进行设置,因此可以将对象传递给useState

const App = () => {
  const [weatherData, setWeatherData] = useState({data: "", time: ""});

  useEffect(() => {
    axios.get(apiUrl).then(response => {
      setWeatherData({...weatherData, data: response.data, time: timestamp});
    });
  }, []);

  return <div>{weatherData && <Weather data={weatherData.data} />}</div>;
};

当我只对useState()和setWeatherData(response.data)进行相同操作时,它工作正常,但我想添加时间

2 个答案:

答案 0 :(得分:1)

您是否尝试过以下方法:

setWeatherData({
  ...response.data,
  time: timestamp,
});

P.S。让我知道我是否正确理解了你。

UPD 其他选项,如果您需要访问当前状态:

useEffect(() => {
  axios.get(apiUrl).then(response => {
    const timestamp = Date.now().timestamp;
  
    setWeatherData((prevWeatherData) => ({
      ...prevWeatherData,
      data: response.data,
      time: timestamp,
    }));
  });
}, []);

答案 1 :(得分:0)

尝试一下:

const App = () => {
    const [weatherData, setWeatherData] = useState(null);

    useEffect(() => {
        async function fetchWeather () {
            const response =  await axios.get(apiUrl)
            setWeatherData({data: response.data, time: new Date().getTime()});
        } 
    
        fetchWeather()
    }, [weatherData]);

    return (
        <>
            {weatherData && <Weather data={weatherData.data} />}
        </>
    );
};