我有一个仪表板组件,该组件从reducer接收状态,然后根据状态为用户呈现帐户信息。该组件在第一个渲染时渲染得很好。但是,当我刷新页面时,一切都消失了,没有任何渲染。我认为useEffect挂钩可能存在问题,可以通过在依赖数组中放置一些值来解决此问题。但是,我意识到,即使问题出在那,不依赖useEffect钩子的组件JSX元素部分仍应呈现。甚至没有发生,刷新时我什么也没得到。我该如何解决?
这里是Github上项目的链接:https://github.com/jevoncochran/Food-Truck-TrackR
这里是组件:
const Dashboard = props => {
const [accountInfo, setAccountInfo] = useState({});
useEffect(() => {
axiosWithAuth()
.get(`/operator/${props.id}`)
.then(res => {
// console.log(res);
setAccountInfo(res.data);
})
.catch(err => console.log(err))
}, [props.id])
return (
<div>
<h1>This is the Dashboard component</h1>
<h2>Welcome, {accountInfo.username}</h2>
<h3>Your Trucks</h3>
{accountInfo.trucks && accountInfo.trucks.map(truck => (
<div key={truck.id}>
<p>{truck.name}</p>
<p>{truck.cuisine_type}</p>
<p>{truck.physical_address}</p>
<br/>
</div>
))}
</div>
)
}
const mapStateToProps = state => {
return {
id: state.account.id,
username: state.account.username,
email: state.account.email
}
}
export default connect(mapStateToProps, {})(Dashboard);
编辑:这就是呈现仪表板组件的方式。仔细阅读人们的评论后,似乎在刷新时,我丢失了state.account.id,这导致我丢失了App.js中的dynamicRoute,这导致了Dashboard组件无法呈现。任何人都可以看到此问题的解决方案:
function App(props) {
console.log(props);
const dynamicRoute = `/api/vendor/${props.accountId}`
return (
<Router>
<div className="App">
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={Register} />
<PrivateRoute path={dynamicRoute} component={Dashboard} />
</div>
</Router>
);
}
有两种方法可以解决此问题。其中之一是执行一个动作,该动作将调用API来检索仪表板组件所需的信息,并在redux状态返回未定义状态时运行该动作,这在刷新时会发生。还有redux-persist。我最终使用redux-persist来解决此问题,有关此文档,请参见https://github.com/rt2zz/redux-persist。这是来自index.js
的代码:
相关进口:
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import { PersistGate } from "redux-persist/integration/react";
// set up to persist redux state on refresh
const persistConfig = {
key: 'root',
storage
};
const persistedReducer = persistReducer(persistConfig, truckReducer);
// async middleware (thunk) and logger has to go here
let store = createStore(persistedReducer, applyMiddleware(thunk, logger));
let persistor = persistStore(store);
ReactDOM.render(
<Provider store={store}>
{/* wrap component in PersistGate for redux persist to take effect */}
<PersistGate loading={null} persistor={persistor}>
<Router>
<App />
</Router>
</PersistGate>
</Provider>,
document.getElementById('root')
);