我有一个应用程序,我希望应用程序组件保存当前登录的用户。我有以下路线和组件。
基本上,我的应用程序中的每个组件都会使用用户对象。当然,我可以将用户作为 props 传递给每个组件,但这并不优雅。全局共享 user prop 的正确 React 方式是什么?
const App = () => {
const [user, setUser] = useState(null);
return (
<Router>
<div className="app">
<Topbar />
<Switch>
<Route path="/login" exact component={Login} />
<Route path="/home" exact component={Home} />
<Route path="/" exact component={ShopMenu} />
<Route path="/orders">
<Orders />
</Route>
<Route path="/wishlist" exact component={Wishlist} />
<Route path="/wallet" exact component={Wallet} />
<Route path="/cart" exact component={Cart} />
</Switch>
<BottomBar />
</div>
</Router>
);
};
Run Code Online (Sandbox Code Playgroud) 这是基于本课程的练习 2.14 https://fullstackopen.com/en/part2/getting_data_from_server。
\n\n用户可以选择一个国家,然后就会显示该国家首都的天气信息。我的代码给出错误无法读取未定义的属性“温度”
\n\nconst Weather = ({ city }) => {\nconst [weatherDetails, setWeatherDetails] = useState([])\n\nuseEffect(() => {\n axios.get(\'http://api.weatherstack.com/current\', {\n params: {\n access_key: process.env.REACT_APP_WEATHER_KEY,\n query: city\n }\n }).then(\n (response) => {\n setWeatherDetails(response.data)\n }\n )\n}, [city])\nconsole.log(\'weather\', weatherDetails);\n\nreturn (\n <div>\n <h3>Weather in {city} </h3>\n {weatherDetails.current.temperature}\n </div>\n)}\nRun Code Online (Sandbox Code Playgroud)\n\n基本上,该行
\n\n{weatherDetails.current.temperature}\nRun Code Online (Sandbox Code Playgroud)\n\n使我的代码崩溃。当我删除该行时,我可以通过 console.log 看到响应,但有两个连续的日志
\n\nweather []\nweather {request: {\xe2\x80\xa6}, location: {\xe2\x80\xa6}, current: {\xe2\x80\xa6}}\nRun Code Online (Sandbox Code Playgroud)\n\n我认为我的代码发生在这两者之间,并且它尝试在数据到达之前访问数据,但我不知道该怎么做才能解决这个问题。
\n\n另外,我不知道 useEffect() 的参数 [city] 是做什么的,所以如果有人能向我解释它的作用那就太好了。
\n\n编辑:解决了!\n将weatherDetail的初始状态设置为null并进行一些条件渲染
\n\nif (weatherDetails) {\n …Run Code Online (Sandbox Code Playgroud)