如何使用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();
noteActions.js
import actionTypes from '../constants/actionTypes';
export const actionNoteGetLatest = () => ({
type: actionTypes.NOTE_GET_LATEST,
});
答案 0 :(得分:3)
问题是您正在渲染初始Main
组件而不是连接组件。通过connect
调用更新该行:
const MainWrapper = connect(null, { actionNoteGetLatest })(Main);
然后,在渲染中使用MainWrapper
组件:
ReactDOM.render(<MainWrapper />, document.getElementById('root'));
检查当前是否正在渲染<Main/>
组件而不提供任何道具。