7-1 處理不同隻api需帶入不同地區名稱的問題 1.建立個api所需使用的locationname 對應表

2.寫比對函式findLocation以拉取api資料所需使用的locationname

只要需入參數會回傳對應的location

export const findLocation = (cityName) => {
  return availableLocations.find((location) => location.cityName === cityName);
};

IMG_3659.jpg

7-2新增地區設定頁面

去views設定weathersetting.js

const WeatherSetting = () => {
  
  return (
    <WeatherSettingWrapper>
      <Title>設定</Title>
      <StyledLabel htmlFor="location">地區</StyledLabel>
//htmlFor是為了避免關鍵字衝突
      <StyledSelect
//下拉式選單
        id="location"
        name="location"
      >
 //用迴圈產生陣列所以你需要匯入availableLocations陣列
        {availableLocations.map(({ cityName }) => (
          <option value={cityName} key={cityName}>
            {cityName}
          </option>
        ))}
      </StyledSelect>

      <ButtonGroup>
        <Back onClick={() => handleCurrentPageChange('WeatherCard')}>返回</Back>
        <Save onClick={handleSave}>儲存</Save>
      </ButtonGroup>
    </WeatherSettingWrapper>
  );
};

做好setting頁面,要在app.js匯入元件

app.js

import WeatherCard from './views/WeatherCard';
import WeatherSetting from './views/WeatherSetting';

所以你現在會看到兩個視窗,如果要讓兩個視窗做切換,你需要在app.js寫條件轉譯

建立一個新的state來決定使用者現在看到哪個頁面

const [currentPage, setCurrentPage] = useState('WeatherCard');

return
      <container>  
        {currentPage === 'WeatherCard' && (
          <WeatherCard
            weatherElement={weatherElement}
            moment={moment}
            fetchData={fetchData}
            handleCurrentPageChange={handleCurrentPageChange}
          />
        )}

        {currentPage === 'WeatherSetting' && (
          <WeatherSetting handleCurrentPageChange={handleCurrentPageChange} />
        )}
       </container> 

7-3 實作 頁面間的切換功能

在天氣頁面裡面右上新增一個齒輪,image裡面有直接使用

IMG_3660.jpg

weathercard.js

import { ReactComponent as CogIcon } from './../images/cog.svg';

樣式
const Cog = styled(CogIcon)`
  position: absolute;
  top: 30px;
  right: 15px;
  width: 15px;
  height: 15px;
  cursor: pointer;
`;

const WeatherCard = () => {
放入元件
return (
    <WeatherCardWrapper>
      <Cog />
    </WeatherCardWrapper>
  );
};      

當使用者去點擊齒輪按鈕的時候修改currentPage資料狀態 需要用到讓子元件修改父層元件的資料狀態

透過父元件將修改資料的方法傳遞到子元件來完成 子元件要如何取得setCurrenPage這個方法?可透過props 在app裡面定義一個handlecurrentPage的函式 並在裡面執行setCurrentPage這個方法,透過props