【问题标题】:How do I fetch async data using dispatch in react js如何在 React js 中使用调度获取异步数据
【发布时间】:2021-01-06 06:08:56
【问题描述】:

我在 react js view recordings.js 中写了以下函数

fetchRecordingJson(file_name)
  {

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

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

  }

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

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

我正在使用 redux-thunk 库进行异步调用,下面是我的 reducer 代码

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);

下面是我的 action.js 代码

export function receiveJSON(json, file_name) {
    return {
        type: RECEIVE_JSON,
        file_name,
        data: json
    }
}

    export  function fetchRecordingJson(file_name) {
    
    return dispatch => {
    
        return  axios.get(API_URL+`fetchjson/${file_name}`)
                .then(json => {
                    
                   dispatch(receiveJSON(json.data, file_name))
    
              
    
                })
       
            }
        }
        

【问题讨论】:

  • 如果你使用react hooks,你应该使用const analysis = useSelector(state => state.<path>),如果是遗留类,使用连接mapStateToProps
  • @venkateshpogartha 不一定是这样,您也可以将 connect 与 react-hooks 一起使用
  • 您的代码似乎正确,当您在console.log(json) 中尝试console.log(json) 时,您是否得到响应调用.then
  • @SinanYaman 如果您可以选择使用钩子,那么使用连接有什么意义。
  • @SinanYaman 是的,我收到了回复,但需要知道如何将数据传递给另一个视图页面,如果使用 history.push 方法是个好主意,那么我如何在另一个页面中控制该数据

标签: reactjs redux redux-thunk


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 2020-03-25
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2018-08-05
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多