Javascript 如何在React中设置默认道具值?

Javascript 如何在React中设置默认道具值?,javascript,reactjs,Javascript,Reactjs,在一个天气项目中,我显示了主温度(温度)、最低温度、最高温度、每小时和每日温度。每个温度值都切换了摄氏度和华氏度单位。最小和最大温度的默认值设置为celcius,但其他值不设置。无论何时刷新,除最小值和最大值外的所有温度值均设置为华氏值 以下是所需的文件 App.js 从“React”导入React; 导入“/App.css”; 从“/components/Weather”导入天气; 从“/components/Spinner”导入微调器; 进口{ 烤面包盒, 干杯 滑动 快速移动 轻弹 反弹

在一个天气项目中,我显示了主温度(温度)、最低温度、最高温度、每小时和每日温度。每个温度值都切换了摄氏度和华氏度单位。最小和最大温度的默认值设置为celcius,但其他值不设置。无论何时刷新,除最小值和最大值外的所有温度值均设置为华氏值

以下是所需的文件

  • App.js
  • 从“React”导入React;
    导入“/App.css”;
    从“/components/Weather”导入天气;
    从“/components/Spinner”导入微调器;
    进口{
    烤面包盒,
    干杯
    滑动
    快速移动
    轻弹
    反弹
    }从“反应迟钝”;
    导入“react-toastify/dist/react-toastify.css”;
    从“/components/forecast/DailyHourly”导入DailyHourly;
    //威瑟比特
    const API_KEY3=process.env.REACT_APP_WEATHER_API_KEY;
    //weatherbit当前、每日和每小时预测
    常数当前_API=`https://cors-anywhere.herokuapp.com/https://api.weatherbit.io/v2.0/current?`;
    const FORECAST_API=`https://cors-anywhere.herokuapp.com/https://api.weatherbit.io/v2.0/forecast/daily?`;
    const HOURLY_API=`https://cors-anywhere.herokuapp.com/https://api.weatherbit.io/v2.0/forecast/hourly?`;
    const sectionStyle={
    背景:“继承”,
    不透明度:“0.42”,
    过滤器:“模糊(1.2px)”,
    背景尺寸:“封面”,
    背景位置:“中心”,
    位置:“绝对”,
    背景:“747d8c”,
    boxShadow:“2rem 0 1rem 0 rgba(255255255,0.05)”,
    边框:“3px实心透明”
    };
    类应用程序扩展了React.Component{
    建造师(道具){
    超级(道具);
    此.state={
    孤岛加载:是的,
    拉丁语:“,
    龙:“,
    说明:“,
    maxTempCel:“”,
    maxTempFahr:“”,
    minTempCel:“”,
    minTempFahr:“,
    小时预测:“,
    单位:“C”,
    cel:“,
    法尔:““
    };
    }
    componentDidMount=async()=>{
    这是我的国家({
    单位:“C”
    });
    //跟踪位置和
    //设置纬度和经度值的状态
    navigator.geolocation.getCurrentPosition(
    异步(位置)=>{
    这是我的国家(
    {
    纬度:位置坐标纬度固定(3),
    lon:位置。坐标。经度。toFixed(3)
    },
    () => {
    这个。fetchWeather();
    }
    );
    },
    (错误)=>{
    toast.error(`${error.message}`{
    自动关闭:3000
    });
    },
    {
    EnableHighAccurance:正确,
    超时:50000,
    最高限额:1000
    }
    );
    };
    onUnitChange=(新单位)=>{
    //console.log(“显示的单位”,newUnit);
    这是我的国家({
    单位:新单位
    });
    };
    fetchWeather=async()=>{
    const{lat,lon}=this.state;
    //首先它从M变为I,然后它不改变
    //console.log(“单元类型”,单元类型);
    //当前天气
    取回(
    `${CURRENT_API}lat=${lat}&lon=${lon}&key=${API_KEY3}`
    //`${CURRENT_API}lat=${lat}&lon=${lon}&key=${API_KEY3}&units=${unitType}`
    )
    .然后((res)=>res.json())
    .然后((responseJson)=>{
    //控制台日志(“当前天气”,responseJson);
    试一试{
    这是我的国家(
    {
    cel:Math.round(responseJson.data[0].temp),
    fahr:Math.round(responseJson.data[0].temp*1.8+32),
    //temp:responseJson.data[0]。temp,
    孤岛加载:false
    },
    () => {
    setItem(“weather”,JSON.stringify(this.state));
    }
    );
    }抓住{
    toast.error(“错误代码429”);
    }
    });
    //天气预报-每日和最大最小值
    fetch(`FORECAST\u API}lat=${lat}&lon=${lon}&days=6&key=${API\u KEY3}`)
    .然后((res)=>res.json())
    .然后((responseJson)=>{
    //控制台日志(“每日天气”,responseJson);
    试一试{
    这是我的国家(
    {
    每日预测:responseJson.data,
    precip:responseJson.data[0].pop,
    maxTempCel:Math.round(responseJson.data[0].max_temp),
    maxTempFahr:Math.round(responseJson.data[0].max_temp*1.8)+32,
    minTempCel:Math.round(responseJson.data[0].min_temp),
    minTempFahr:Math.round(responseJson.data[0].min_temp*1.8)+32,
    孤岛加载:false
    },
    () => {
    console.log(“每日”,this.state.dailyforecast);
    setItem(“weather”,JSON.stringify(this.state));
    }
    );
    }抓住{
    toast.error(“请求太多”);
    }
    });
    //天气预报-每小时
    fetch(`${HOURLY\u API}lat=${lat}&lon=${lon}&hours=10&key=${API\u KEY3}`)
    .然后((res)=>res.json())
    .然后((responseJson)=>{
    试一试{
    这是我的国家(
    {
    小时预测:responseJson.data,
    孤岛加载:false
    },
    () => {
    setItem(“weather”,JSON.stringify(this.state));
    }
    );
    }抓住{
    toast.error(“请稍候”);
    }
    });
    };
    render(){
    const{isLoading,dailyforecast,hourlyforecast,precip}=this.state;
    返回(
    {孤岛加载(
    ) : (
    {/*天气预报卡*/}
    {/*天气详情*/}
    {/*预测卡*/}
    

    {/*预测卡结束*/}
    import React from "react";
    import "./App.css";
    import Weather from "./components/Weather";
    import Spinner from "./components/Spinner";
    import {
      ToastContainer,
      toast,
      Slide,
      Zoom,
      Flip,
      Bounce
    } from "react-toastify";
    import "react-toastify/dist/ReactToastify.css";
    import DailyHourly from "./components/forecast/DailyHourly";
    
    // weatherbit
    const API_KEY3 = process.env.REACT_APP_WEATHER_API_KEY;
    
    // weatherbit current, daily and hourly forecast
    const CURRENT_API = `https://cors-anywhere.herokuapp.com/https://api.weatherbit.io/v2.0/current?`;
    
    const FORECAST_API = `https://cors-anywhere.herokuapp.com/https://api.weatherbit.io/v2.0/forecast/daily?`;
    
    const HOURLY_API = `https://cors-anywhere.herokuapp.com/https://api.weatherbit.io/v2.0/forecast/hourly?`;
    
    const sectionStyle = {
      background: "inherit",
      opacity: "0.42",
      filter: "blur(1.2px)",
      backgroundSize: "cover",
      backgroundPosition: "center",
      position: "absolute",
      background: "#747d8c",
      boxShadow: "2rem 0 1rem 0 rgba(255,255,255,0.05)",
      border: "3px solid transparent"
    };
    
    class App extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          isLoading: true,
          lat: "",
          lon: "",
          description: "",
          maxTempCel: "",
          maxTempFahr: "",
          minTempCel: "",
          minTempFahr: "",
          hourlyforecast: "",
          unit: "C",
          cel: "",
          fahr: ""
        };
      }
    
      componentDidMount = async () => {
        this.setState({
          unit: "C"
        });
        // Tracking the location and
        // Setting the state of latitude and longitude values
        navigator.geolocation.getCurrentPosition(
          async (position) => {
            this.setState(
              {
                lat: position.coords.latitude.toFixed(3),
                lon: position.coords.longitude.toFixed(3)
              },
              () => {
                this.fetchWeather();
              }
            );
          },
          (error) => {
            toast.error(`${error.message}`, {
              autoClose: 3000
            });
          },
          {
            enableHighAccuracy: true,
            timeout: 50000,
            maximumAge: 1000
          }
        );
      };
    
      onUnitChange = (newUnit) => {
        //console.log("UNIT SHOWN", newUnit);
        this.setState({
          unit: newUnit
        });
      };
    
      fetchWeather = async () => {
        const { lat, lon } = this.state;
    
        // First it changes from M to I and then it doesn't change
        //console.log("UNIT TYPE", unitType);
    
        // Current Weather
        fetch(
          `${CURRENT_API}lat=${lat}&lon=${lon}&key=${API_KEY3}`
          // `${CURRENT_API}lat=${lat}&lon=${lon}&key=${API_KEY3}&units=${unitType}`
        )
          .then((res) => res.json())
          .then((responseJson) => {
            //console.log("Current Weather", responseJson);
            try {
              this.setState(
                {
                  cel: Math.round(responseJson.data[0].temp),
                  fahr: Math.round(responseJson.data[0].temp * 1.8 + 32),
                  // temp: responseJson.data[0].temp,
                  isLoading: false
                },
                () => {
                  localStorage.setItem("weather", JSON.stringify(this.state));
                }
              );
            } catch {
              toast.error("Error Code 429");
            }
          });
    
        // Forecast Weather - Daily and Min Max
        fetch(`${FORECAST_API}lat=${lat}&lon=${lon}&days=6&key=${API_KEY3}`)
          .then((res) => res.json())
          .then((responseJson) => {
            //console.log("Daily Weather", responseJson);
            try {
              this.setState(
                {
                  dailyforecast: responseJson.data,
                  precip: responseJson.data[0].pop,
                  maxTempCel: Math.round(responseJson.data[0].max_temp),
                  maxTempFahr: Math.round(responseJson.data[0].max_temp * 1.8) + 32,
                  minTempCel: Math.round(responseJson.data[0].min_temp),
                  minTempFahr: Math.round(responseJson.data[0].min_temp * 1.8) + 32,
                  isLoading: false
                },
                () => {
                  console.log("DAILY", this.state.dailyforecast);
                  localStorage.setItem("weather", JSON.stringify(this.state));
                }
              );
            } catch {
              toast.error("Too many requests");
            }
          });
    
        // Forecast Weather - Hourly
        fetch(`${HOURLY_API}lat=${lat}&lon=${lon}&hours=10&key=${API_KEY3}`)
          .then((res) => res.json())
          .then((responseJson) => {
            try {
              this.setState(
                {
                  hourlyforecast: responseJson.data,
                  isLoading: false
                },
                () => {
                  localStorage.setItem("weather", JSON.stringify(this.state));
                }
              );
            } catch {
              toast.error("Please wait some time");
            }
          });
      };
    
      render() {
        const { isLoading, dailyforecast, hourlyforecast, precip } = this.state;
    
        return (
          <React.Fragment>
            <div className="container" style={{ marginTop: "1.8em" }}>
              <div className="row">
                <div className="col-sm-4 form-container">
                  <ToastContainer
                    transition={Bounce}
                    className="toast-background"
                  />
                </div>
    
                {isLoading ? (
                  <Spinner />
                ) : (
                  <React.Fragment>
                    <div className="col-sm-8 image-container">
                      {/* Weather Card */}
                      <div className="background">
                        <div className="container">
                          <div
                            id="card"
                            className="weather"
                            style={sectionStyle}
                          ></div>
    
                          <div
                            id="card"
                            className="weather2"
                            style={{ background: "" }}
                          >
                            <div className="details">
                              {/* Weather Details */}
                              <div className="content" style={{ width: "105px" }}>
                                <Weather
                                  cel={this.state.cel}
                                  fahr={this.state.fahr}
                                  maxTempCel={this.state.maxTempCel}
                                  maxTempFahr={this.state.maxTempFahr}
                                  minTempCel={this.state.minTempCel}
                                  minTempFahr={this.state.minTempFahr}
                                  changeUnit={this.onUnitChange}
                                  unit={this.state.unit}
                                />
                              </div>
    
                              {/* Forecast Cards */}
    
                              <div
                                className="content"
                                style={{ width: "400px", marginTop: "-40px" }}
                              >
                                <br />
                                <br />
                                <DailyHourly
                                  unit={this.state.unit}
                                  timezone={this.state.timezone}
                                  dailyforecast={dailyforecast}
                                  hourlyforecast={hourlyforecast}
                                />
                              </div>
                              {/* Forecast Cards Ends*/}
                            </div>
                          </div>
                        </div>
                      </div>
                      {/* Video Background Starts */}
    
                      {/* Video Background Ends */}
                    </div>
                    {/* Weather Card Ends */}
                  </React.Fragment>
                )}
              </div>
            </div>
          </React.Fragment>
        );
      }
    }
    
    export default App;
    
    import React from "react";
    import "./Weather.css";
    import uparrow from "../images/up-arrow.png";
    import downarrow from "../images/down-arrow2.png";
    import CelToFahr from "./CelToFahr";
    import CountUp from "react-countup";
    import CelToFa from "./CelToFa";
    
    const Weather = (props) => {
      // For CelToFahr component
      const sendNewUnitToParent = (newUnit) => {
        //console.log("Unit I get", newUnit);
        props.changeUnit(newUnit);
      };
    
      return (
        <div>
          {/* <CelToFa onSelectedTempUnit={newTempUnit} /> */}
          <CelToFahr onUnitChange={sendNewUnitToParent} />
          {/* {props.temp && props.temp === 0 ? (
            <div className="glow">
              {Math.trunc(props.temp)}°<h5>{props.unit === "C" ? "C" : "F"}</h5>{" "}
            </div>
          ) : (
            <div className="glow">
              {Math.trunc(props.temp)}°<h5>{props.unit === "C" ? "C" : "F"}</h5>
            </div>
          )} */}
          {console.log("PROPS", props)}
          <>
            <CountUp
              start={props.unit === "C" ? props.fahr : props.cel}
              end={props.unit === "F" ? props.fahr : props.cel}
              duration={2}
            >
              {({ countUpRef, start }) => (
                <h1 style={{ color: "white" }} ref={countUpRef}></h1>
              )}
            </CountUp>
            {}° {props.unit === "C" ? "C" : "F"}
          </>
          <div style={{ width: "100%" }}>
            <div style={{ width: "50%", display: "inline-block" }}>
              {props.minTempCel && props.minTempFahr === 0 ? (
                <h6 style={{ color: "white" }}>
                  <strong>
                    <img src={downarrow} />
                    0°
                  </strong>
                </h6>
              ) : (
                <strong>
                  <img src={downarrow} />
                  <CountUp
                    start={
                      props.unit === "F" ? props.minTempCel : props.minTempFahr
                    }
                    end={props.unit === "C" ? props.minTempCel : props.minTempFahr}
                    duration={2}
                  >
                    {({ countUpRef, start }) => (
                      <h6 style={{ color: "white" }} ref={countUpRef}></h6>
                    )}
                  </CountUp>
                  {}° {props.unit === "C" ? "C" : "F"}
                </strong>
              )}
            </div>
            <div style={{ width: "50%", display: "inline-block" }}>
              {props.maxTempCel && props.maxTempFahr === 0 ? (
                <h6 style={{ color: "white" }}>
                  <strong>
                    <img src={uparrow} />
                    0°
                  </strong>
                </h6>
              ) : (
                <strong>
                  <img src={uparrow} />
                  <CountUp
                    start={
                      props.unit === "F" ? props.maxTempCel : props.maxTempFahr
                    }
                    end={props.unit === "C" ? props.maxTempCel : props.maxTempFahr}
                    duration={2}
                  >
                    {({ countUpRef, start }) => (
                      <h6 style={{ color: "white" }} ref={countUpRef}></h6>
                    )}
                  </CountUp>
                  {}° {props.unit === "C" ? "C" : "F"}
                </strong>
              )}
            </div>
          </div>
    
          {<hr style={{ color: "white" }} />}
        </div>
      );
    };
    
    export default Weather;
    
    import React, { Component } from "react";
    import "./CelToFahr.css";
    
    class CelToFahr extends Component {
      state = {
        celOn: false,
        unit: "F"
      };
    
      changeUnit = () => {
        this.setState({ celOn: !this.state.celOn });
        const newUnit = this.state.celOn === false ? "F" : "C";
        this.props.onUnitChange(newUnit);
      };
    
      render() {
        return (
          <div className="toggle-button-cover">
            <div className="button r" id="button-3">
              <input
                type="checkbox"
                className="checkbox"
                onClick={this.changeUnit}
              />
              <div className="knobs"></div>
              <div className="layer"></div>
            </div>
          </div>
        );
      }
    }
    
    export default CelToFahr;