我有一个使用React构建的简单天气应用程序.App.js
代码在其return()
语句中包括以下内容:
<Routes>
<Route exact path="/" element={<Form />} />
<Route exact path="/weather/*" element={<Weather />} />
</Routes>
Form.jsx
接受用户输入,设置为状态,如下所示:
export default function Form() {
const [zipCode, setZipCode] = useState('');
const getZip = (e) => {
e.preventDefault();
setZipCode(e.target[0].value);
}
return (
<div>
<form onSubmit={getZip}>
<input id="zip" />
<label htmlFor="zip">Your Zip Code</label>
<Link to="/Weather" role="button" type="submit" className="btn btn-primary">Enter</Link>
</form>
)}
Weather.jsx
应该使用该邮政编码并进行API调用以获取天气数据:
function Weather() {
const { zipCode } = useParams();
const [forecastObj, setForecastObj] = useState({});
useEffect(() => {
fetch(`https://apiservice.com/forecast/loc=${zipCode}`)
}
该应用程序应该显示Form.jsx
,并在提交邮政编码后切换到Weather.jsx
.当我输入邮政编码时,我得到一个错误:GET https://apiservice.com/forecast/loc=undefined 400
,所以邮政编码没有被传递到Weather.jsx
.我通过google找到的大多数资源似乎都是针对旧版本的(很多是this.state = state
或类似版本).其他资源说使用useParams
,这是我在Weather.jsx
中设置的.
我错过了什么?