返回

javascript-解构useContext对象

发布时间:2022-07-22 13:30:39 272
# 前端

尽管我重复名称weather.weather两次以获得特定值,但我目前正在使用useContext很好地导入数据。我想用数据解构变量,以免在获取数据时重复两次天气。这是我目前的出口:

import { createContext, useState, useEffect } from 'react';
import { Weather } from '../../types';
import axios from 'axios';
import { WeatherContextType, WeatherContextProviderProps } from '../../types';

export const WeatherContext = createContext(null);

export const WeatherContextProvider = ({ children }: WeatherContextProviderProps) => {
  const [weather, setWeather] = useState();
  const fetchWeatherData = async () => {
    const response = await axios.get('http://mock-api-call/weather/get-weather');

    setWeather(response.data.result.weather);
  };

  useEffect(() => {
    fetchWeatherData();
  }, []);
  return (
    {children}
  );
};

我在哪里导入数据:

import { WeatherContext } from './context/WeatherContext';
import { Title, Text, Container } from '@mantine/core';
import { useContext } from 'react';

const WeatherComponent = () => {
  const weather = useContext(WeatherContext);
  console.log(weather);

  return (
      
      
        {weather?.weather?.forcast} with a low of {weather?.weather?.min} and a high of{' '}
        {weather?.weather?.max}
      
      
        {weather?.weather?.description}
      
    
  );
};

export default WeatherComponent;

我想我可以做一些简单的事情,比如:

const {weather} = useContext(WeatherContext);

尽管我后来发现了这个错误:

Property 'weather' does not exist on type 'WeatherContextType | null'.

正如我提到的代码有效,我真的只是想美化它。

天气上下文类型:

export type WeatherContextType = {
  weather: Weather | null | undefined;
  setWeather: React.Dispatch<React.SetStateAction>;
};
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(1)
按点赞数排序
用户头像