我正在尝试使用React和Redux制作一个web应用程序。还原器调用后端的api,此api返回类别的Json。但我意识到,当我从组件函数调用这个还原器和状态时,因为某个原因,包含状态的div被呈现了两次。在第一个呈现中,类别的json数组不存在,而在第二个呈现中,类别的json数组存在。
这是我的组件代码:
import React, { useRef, useEffect} from 'react'
import { NavLink, Link } from 'react-router-dom'
import { connect } from 'react-redux'
import PrivateMenu from '../Molecules/PrivateMenu'
import PublicMenu from '../Molecules/PublicMenu'
<div className="header-list-categories-container">
<div className="sub-list-container">
<label htmlFor="">{console.log('')}</label>
<label htmlFor="">{console.log('the div X starts')}</label>
<label htmlFor="">{console.log(thecategories)}</label>
<label htmlFor="">{thecategories?console.log('the array exists'):console.log('the array does not exists')}</label>
<label htmlFor="">{console.log('the div X ends')}</label>
</div>
</div>
const mapStateToProps = state =>(
{
thecategories : state.categoriaReducer.categories
}
)
export default connect(mapStateToProps)(Header)这是我对组件函数头的app.jsx调用:
import React from 'react';
import '../App.css';
import { BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import Header from './Organisms/Header'
import Home from './pages/Home'
const App = ()=>(
<Router>
<Header />
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</Router>
)
export default App;这是我的index.js调用app.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import store from './redux/store'
import { Provider } from 'react-redux'
import { getallcategories} from './redux/actionCreators'
store.dispatch(getallcategories())
ReactDOM.render(
<Provider store ={store}>
<App />
</Provider>
,document.getElementById('root'));发布于 2020-05-19 18:33:52
在从后端异步获取数据时,您所描述的似乎是一种正常的行为--一个组件在挂载期间没有数据呈现,然后当它的道具更改(react-redux注入它们)时,按照它应该的方式对实际数据进行重新处理。
一般的约定是,当还没有可用的数据时,向用户显示一些信息--无论是加载旋转器还是自定义的“空列表”组件。
示例:
// your Header component would look like so
// I've defaulted the 'thecategories' prop to an empty array for ease of use
const Header = ({ thecategories = []}) => {
if (thecategories.length === 0) {
return (<div>No data available.</div>);
} else {
return (
<div className="header-list-categories-container">
<div className="sub-list-container">
<label htmlFor="">{console.log('')}</label>
<label htmlFor="">{console.log('the div X starts')}</label>
<label htmlFor="">{console.log(thecategories)}</label>
<label htmlFor="">{console.log('the array always exists at this point ;)')}</label>
<label htmlFor="">{console.log('the div X ends')}</label>
</div>
</div>)
};
);https://stackoverflow.com/questions/61897963
复制相似问题