如何将Redux连接到React功能组件

时间:2019-04-21 13:11:05

标签: reactjs redux

我得到的错误是“ TypeError:无法设置未定义的属性'props'”。

我试图做的是将redux连接到我的功能性(无状态)组件。 我想我写错了,但是我不知道如何正确地编写它并使之工作。

import React from 'react'
import { connect } from 'react-redux'


const Logger = (props) => {
    console.log(props.event);

    let logger = []

    if(localStorage.getItem("logger")){
      logger = JSON.parse(localStorage.getItem("logger"))
    }

    let d = new Date();
    let h = d.getHours();
    let m = d.getMinutes();
    let s = d.getSeconds();
    let time = (h + ":" + m + ":" + s)

    logger.push(
      {
        time: time,
        event: props.event
      }
    )

    localStorage.setItem("logger", JSON.stringify(logger))
    props.logger(logger)
}

const mapDispatchToProps = (dispatch) =>{
  return{
    logger: (value) => {
      dispatch({
        type: 'LOGGER',
        payload: value
      })
    }
  }
} 

export default connect(null, mapDispatchToProps)(Logger)


1 个答案:

答案 0 :(得分:0)

您可以做的是将其设置为LoggerService,而不是功能组件。 该服务将有一个名为log的方法,该方法将具有您当前Logger组件中的所有代码。看起来像这样:

import store from '../path-to-store';

class LoggerService {
  function log(event) {
    let logger = []

    if(localStorage.getItem("logger")){
      logger = JSON.parse(localStorage.getItem("logger"))
    }

    let d = new Date();
    let h = d.getHours();
    let m = d.getMinutes();
    let s = d.getSeconds();
    let time = (h + ":" + m + ":" + s)

    logger.push(
      {
        time: time,
        event: event // note: no 'props' anymore
      }
    )

    localStorage.setItem("logger", JSON.stringify(logger));

    // note: dispatching events directly from store
    store.dispatch((value) => {
      dispatch({
        type: 'LOGGER',
        payload: value
      })
    });
  }
}

然后,无论您需要记录什么内容,只需致电LoggerService.log(someEvent)。它可能在

class MyComponent extends React.Component {
    componentDidMound () => {
        // you have your event here somehow
        LoggerService.log(myEvent);
    }
    // render method and other stuff...
}

大注释:这未经测试,仅用于说明概念。 :)