首页 > 解决方案 > Redux 提供程序未在加载时为 React 组件提供道具

问题描述

我正在使用 Redux 进行状态管理。我收到道具未定义的错误。下面的块显示了我的代码,

index.js

ReactDOM.render(
      <Provider store={configureStore()}>
        <App />
      </Provider>,
      document.getElementById('root')
  );

store.js

function configureStore(state = { rotating: true }) {
  return createStore(rotateReducer,state);
}

浏览器控制台:

App {props: undefined, context: undefined, refs: {…}, updater: {…}}
on expand this App object in console, 
props: {rotating: true, startAction: ƒ, stopAction: ƒ} (now props are defined).

应用程序.js

function App() {
    return (
      <div className="App">
        <header className="App-header">
        <img 
            src={logo} 
            className={
              "App-logo" + 
              (this.props.rotating ? "":" App-logo-paused")
            } 
            alt="logo" 
            onClick={
              this.props.rotating ? 
                this.props.stopAction : this.props.startAction
            }
          />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }

export default connect(mapStateToProps, mapDispatchToProps)(App);

App 组件加载的道具有什么问题?

标签: reactjsreduxreact-redux

解决方案


去掉thisprops 之前的关键字,它是一个函数组件,只thisclass组件中使用。

并在函数签名中添加 props 参数。

尝试这个

例子:

import React from "react";
import { connect } from "react-redux";

function App(props) {
  return (
    <div className="App">
      <header className="App-header">
        <img
          src={logo}
          className={
            "App-logo" + (props.rotating ? "" : " App-logo-paused")
          }
          alt="logo"
          onClick={
            this.props.rotating ? props.stopAction : props.startAction
          }
        />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

const mapStateToProps = state => ({ ...state });
const mapDispatchToProps = dispatch => ({
  startAction: () => dispatch(startAction),
  stopAction: () => dispatch(stopAction)
});

export default connect(mapStateToProps, mapDispatchToProps)(App);


推荐阅读