【发布时间】:2020-09-05 22:13:39
【问题描述】:
我正在尝试使用 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'));
【问题讨论】:
-
你的组件代码显然不是真正的代码! (它不是一个函数,只是文件中间的一些 jsx!),但是你真的有问题吗? React 将渲染它两次:首先在开始编译时,然后在这个“getllcategories”异步方法更新你的状态后再次编译......
-
对你的api的调用是异步的,所以在等待从ali返回的类别时,它会首先渲染组件,具有空类别。然后它会在调用完成后重新渲染。
标签: javascript reactjs redux