【问题标题】:How to pass state from redux to class based component?如何将状态从 redux 传递到基于类的组件?
【发布时间】:2019-08-02 13:47:24
【问题描述】:

由于我对所有这些东西都不熟悉,我在从 redux 传递(读取)状态到 react 基于类的组件时遇到了一些麻烦。

在基于类的组件上,我添加了 connect 和 mapStateToProps,但我不知道如何访问它。

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

    class MyComp extends Component {
        render() { 
            return (
               <div>
                   // data from props
                </div>
           )
        }
     }


const mapStateToProps = state => ({
    getVal: state.testReducer.testState
});

export default connect(mapStateToProps)(MyComp);

我正在寻找的是从那个状态中获得价值。 一些详细的例子、教程或类似的东西我们会很好,这样我可以更好地理解它。

对不起,这可能是菜鸟问题...

我一直在寻找读取、设置和将数据传入和传出 redux 以及在组件之间传递的内容,但我感到不知所措,希望得到一些澄清。

【问题讨论】:

  • 当您使用 HOC 连接时,它会将这个值传递给您的道具。您可以通过this.props.getVal 访问它
  • this.props.getVal ?
  • 是的。我建议你先阅读 react 文档。
  • 请查看文档的"Redux conect" 部分。

标签: reactjs react-redux


【解决方案1】:

您只需使用this.props.getVal 进行访问。 所有使用mapStateToProps 正确映射的属性都被注入到组件道具中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2021-04-11
    • 2016-11-26
    • 1970-01-01
    • 2018-06-28
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多