在使用Redux时,我是个菜鸟,我遇到了从API检索数据并通过Redux道具访问数据的问题。当我尝试访问通过操作检索的数据时,它返回未定义的信息。
这是我尝试使用数据的组件:
import React, { Component } from 'react';
import dsteem from 'dsteem';
import { Client } from 'dsteem';
import jsonQuery from 'json-query';
import { connect } from 'react-redux';
import { fetchUtopian } from '../actions/Utopian-action';
class Utopian extends Component {
componentDidMount() {
this.props.fetchUtopian();
}
render() {
console.log(this.props.data);
return (
<div className="utopian-container">
</div>
);
}
}
const mapDispatchToProps = dispatch => ({
fetchUtopian: () => dispatch(fetchUtopian())
})
const mapStateToProps = state => ({
data: state.utopianReducer
})
export default connect(mapStateToProps, mapDispatchToProps)(Utopian);
这是正在检索数据的操作。我在操作中进行了API调用,但我认为它的格式不正确。同样,我是Redux新手。
import dsteem from 'dsteem';
import { Client } from 'dsteem';
export function fetchUtopian() {
return function (dispatch) {
dispatch({ type: "FETCH_UTOPIAN" });
const client = new Client('https://api.steemit.com')
var utopianHot = {
tag: 'utopian-io',
limit: 20
}
client.database
.getDiscussions('hot', utopianHot)
.then((response) => {
dispatch({ type: "FETCH_UTOPIAN_FULFILLED", payload: response.data })
})
.catch((err) => {
dispatch({ type: "FETCH_UTOPIAN_REJECTED", payload: err })
})
}
}
这是减速器:
export default function reducer (state={
utopianCash: [],
fetching: false,
fetched: false,
error: null,
}, action) {
switch (action.type) {
case "FETCH_UTOPIAN": {
return {...state, fetching: true}
}
case "FETCH_UTOPIAN_REJECTED": {
return {...state, fetching: false, error: action.payload}
}
case "FETCH_UTOPIAN_FULFILLED": {
return {
...state,
fetching: false,
fetched: true,
utopianCash: action.payload
}
}
}
return state;
}
组合减速器
// Combine Reducers in this file and export them
import { combineReducers } from 'redux'
import utopianReducer from './Utopian-reducer';
export default combineReducers({
utopianReducer
})
response.data
中的"FETCH_UTOPIAN_FULFILLED"
返回未定义。尝试在乌托邦组件中使用this.props.data
或this.props.data.utopianCash
也会返回undefined。
如何在操作中成功从API中检索数据,然后在组件中使用它?