提议在componentDidMount中不可用

问题描述 投票:0回答:1

如何使用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,
});
javascript reactjs redux
1个回答
3
投票

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

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.