【问题标题】:Using redux data in JS object在 JS 对象中使用 redux 数据
【发布时间】:2019-12-31 11:24:01
【问题描述】:

我在这里要做的是从 redux 存储中获取数据并在 Options 对象中使用它。我不知道如何用来自 redux 的数据填充 Options obj 的一部分。在 redux-logger 中,我看到一切正常,数据以 redux 状态存储。我认为问题可能在于访问 Options 对象中的道具,但不知道如何传递这些道具。 Highcharts用于数据展示。

从 mapStateToProps 访问数据的 this.props.myValue 是否仅在连接到 redux 存储的 react 组件内部起作用?

import React from 'react'
import { connect } from 'react-redux'
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'

import PreviewNav from '../../../components/preview-nav/preview-nav.component'

import './price-history.styles.scss'

const Options = {
    chart: {
        type: 'line'
    },
    title: {
        text: 'Price History'
    },
    xAxis: {
        title: {
            text: 'Date of change'
        },
        categories: [...this.props.time]
    },
    yAxis: {
        title: {
            text: 'Price in $'
        }
    },
    series: [
        {
            name: 'Price',
            data: [...this.props.price]
        }
    ]
}

const PriceHistory = ({ match }) => {
    console.log(this.props.time)
    return (
        <div>
            <PreviewNav id={match.params.id} />
            <HighchartsReact highcharts={Highcharts} options={Options} />
        </div>
    )
}

const mapStateToProps = state => {
    return {
        price: state.itms.quantityChanges.value,
        time: state.itms.quantityChanges.time
    }
}

connect(mapStateToProps)(Options)
export default PriceHistory

【问题讨论】:

  • 是的,你必须用连接包裹 PriceHistory 组件

标签: reactjs redux highcharts


【解决方案1】:

答案是肯定的,您只能在组件内部访问道具。 尝试这样做

const setOptions (props) = {
const Options = {
    chart: {
        type: 'line'
    },
    title: {
        text: 'Price History'
    },
    xAxis: {
        title: {
            text: 'Date of change'
        },
        categories: [...props.time]
    },
    yAxis: {
        title: {
            text: 'Price in $'
        }
    },
    series: [
        {
            name: 'Price',
            data: [...props.price]
        }
    ]
}
}

【讨论】:

    【解决方案2】:

    将最后两行改为,

    export default connect(mapStateToProps)(PriceHistory);
    

    要连接组件,我们必须将组件作为函数参数传递给 connect api。

    【讨论】:

      猜你喜欢
      • 2016-08-24
      • 1970-01-01
      • 2022-06-11
      • 2016-12-24
      • 2018-05-28
      • 2021-12-17
      • 1970-01-01
      • 2021-07-10
      • 2020-10-05
      相关资源
      最近更新 更多