javascript - React:功能组件渲染两次相同的Div
问题描述
我正在尝试使用 React 和 Redux 制作一个 Web 应用程序。一个reducer调用我后端的一个api,这个api返回一个类别的Json。但是我意识到,当我调用这个reducer 并且来自组件的状态时,出于某种原因,包含状态的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'));
解决方案
您所描述的似乎是从后端异步获取数据时的正常行为 - 组件在挂载期间呈现没有数据,然后,当它的道具发生变化(react-redux
注入它们)时,React 会按照实际情况重新呈现它数据。
一般约定是在还没有可用数据时向用户显示一些信息——加载微调器或自定义“空列表”组件。
例子:
// 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>)
};
);
推荐阅读
- node.js - 值与 bot 和 mysql 数据库的通信不正确
- flutter - 在 Flutter 中创建类的新对象 vs. Navigator
- java - 在java中解密加密的二进制文件(AES_CTR模式)
- python - 需要一次读取 10 个 url 以加快 python 中的抓取速度。存储在 csv 文件中的 url
- elixir - 对 Elixir 中运行时和库的困惑
- angular - angular : 上传视频、音频、doc文件
- html - 搜索栏不接受关闭按钮
- firebase - 如何在列表视图中显示异步函数的结果
- r - 如何将整个 data.frame 转换为数字
- hadoop - 用于平面数据结构的 Apache Parquet