如何在 react js 中使用 dispatch 获取异步数据

时间:2021-01-06 06:08:56

标签: reactjs redux redux-thunk

我在react js视图recordings.js中编写了以下函数

const windowsApp = require("windows-app")
 
const {select, close} = await windowsApp("Microsoft.WindowsCalculator_8wekyb3d8bbwe!App") // Calculator app
 
await select.name_("One").click()
await select.name_("Plus").click()
await select.name_("Two").click()
await select.name_("Equals").click()
const result = Number((await select.accessibilityId("CalculatorResults").getText()).replace("Display is", ""))
 
console.log(`The result of 1 + 2 is ${result}`)
//=> "The result of 1 + 2 is 3"
 
await close()

我想将来自使用函数 fetchrecordingJson(file_name) 的数据传输到另一个页面记录分析

查询是: 如何在记录分析页面中查看来自函数 fetchrecordingJson(file_name) 的数据

我使用 redux-thunk 库进行异步调用,下面是我的减速器代码

fetchRecordingJson(file_name)
  {

    const { dispatch, history } = this.props;
    
    if(dispatch)
    {
     
       dispatch(fetchrecordingJson(file_name));

       history.push('/app/recording-analysis');
  
    }
  

  }

下面是我的 action.js 代码

case 'RECEIVE_JSON':
            let newState = {data: action.data.data, info: action.data.info, count: state.count};
                newState.annotations = action.data.annotations.length === 0 ? [[]] :  action.data.annotations || [[]];
                newState.file_name = action.file_name;
            return Object.assign({}, newState);

1 个答案:

答案 0 :(得分:0)

可以使用redux的mapStateToProps属性获取redux store中保存的数据。我创建了一个示例组件,其中我们通过调用 newState 获取您刚刚存储在 componentDidMount 中的 redux 存储中的 this.props.data 值。

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

class TestOne extends Component {

    componentDidMount = () => {
        console.log(this.props.data)
    }

  render() {
    return (
      <>
      </>
    )
  }
}

const mapStateToProps = state => {
  return {
    data: state.newState
  }
}

export default connect( mapStateToProps )(TestOne)