繁体   English   中英

Prop 在 componentDidMount 中不可用

[英]Prop not available in componentDidMount

我如何使用 redux 触发 actionCreator 来获取我的初始数据。 当应用程序加载时,我需要一个地方来获取我的初始数据。

我把它放在这里但是actionNoteGetLatest是一个道具。 请你帮忙。

 componentDidMount() { // This is where the API would go to get the first data. // Get the notedata. this.props.actionNoteGetLatest(); }

 import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; // Redux import { Provider, connect } from 'react-redux'; // TODO: Add middle ware // import { createStore, combineReducers, applyMiddleware } from 'redux'; import { createStore } from 'redux'; import { PropTypes } from 'prop-types'; // Componenets import PageHome from './components/pages/PageHome'; import PageOther from './components/pages/PageOther'; import registerServiceWorker from './registerServiceWorker'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import '../node_modules/font-awesome/css/font-awesome.min.css'; import './styles/index.css'; import rootReducer from './Reducers/index'; import { actionNoteGetLatest } from './actions/noteActions'; // TODO: Turn redux devtools off for production // const store = createStore(combineReducers({ noteReducer }), {}, applyMiddleware(createLogger())); /* eslint-disable no-underscore-dangle */ const store = createStore( rootReducer, {}, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), ); /* eslint-enable */ class Main extends Component { // constructor(props) { // super(props); // this.state = { // }; // } componentDidMount() { // This is where the API would go to get the first data. // Get the notedata. this.props.actionNoteGetLatest(); console.log(this); } render() { return ( <Provider store={store}> <div className="Main"> <Router> <Switch> <Route exact path="/" component={PageHome} /> <Route path="/other" component={PageOther} /> </Switch> </Router> </div> </Provider> ); } } connect(null, { actionNoteGetLatest })(Main); Main.propTypes = { actionNoteGetLatest: PropTypes.func.isRequired, }; ReactDOM.render(<Main />, document.getElementById('root')); registerServiceWorker();

注意动作.js

 import actionTypes from '../constants/actionTypes'; export const actionNoteGetLatest = () => ({ type: actionTypes.NOTE_GET_LATEST, });

问题是您正在渲染初始Main组件而不是连接的组件。 connect调用更新为:

const MainWrapper = connect(null, { actionNoteGetLatest })(Main);

然后,在渲染中使用MainWrapper组件:

ReactDOM.render(<MainWrapper />, document.getElementById('root'));

检查当前您是否在不提供任何道具的情况下渲染<Main/>组件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM