React Redux Thunk with Typescript make api request

时间:2017-08-02 22:33:57

标签: typescript react-redux redux-thunk react-tsx

我一直在尝试向第三方API发出简单的网址请求。这是我正在进行的项目(https://github.com/JMStudiosJoe/ReactPractice/tree/JMStudiosReact)。我一直在观看Dan Abramov的视频,跟着这个example from redux docsexample,似乎遗漏了一些小东西,因为日志显示我的API数据已经收到并发送到reducer但是状态为某些原因不会被送回组件。 以下是代码摘要:

// app.tsx:获取商店并使用react-reactx中的Provider



import * as React from 'react'
import * as ReactDOM from 'react-dom'
import store from './redux/store/store'
import { Provider } from 'react-redux'
import { getAddressData } from './redux/actions/voteSmartActions'
import {UIRouter, UIView, UISref, UISrefActive, pushStateLocationPlugin} from 'ui-router-react';
import NavigationBarComponent from './components/navigationBarComponent'

store.dispatch(getAddressData(''))

ReactDOM.render(
    <Provider store={store}>
        <NavigationBarComponent userType='buyer' />
    </Provider>,
    document.getElementById("root")
);
&#13;
&#13;
&#13;

有问题的组件从projectsComponent.tsx文件

加载

&#13;
&#13;
if(projectName == 'Vote Smart Locally' ) {
        return (
            <VoteSmartLocallyComponent />
        )
}
&#13;
&#13;
&#13;

// voteSmartLocallyComponent.tsx

&#13;
&#13;
import * as React from 'react'
import { connect } from 'react-redux'
import { getAddressData } from '../../redux/actions/voteSmartActions'
import store from "../../redux/store/store"
interface VoteSmartState {
    address: string
    userAddressData?: any
}
interface VoteSmartProps {
    fetchAddressData: any 
}
const API_KEY = 'AIzaSyCWhwRupMs7IeE4IrGEgHtT0Nt-IGZnP9E'
const endURL = '&key='+ API_KEY
const baseRepURL = 'https://www.googleapis.com/civicinfo/v2/representatives?address='
const baseElectionsURL = 'https://www.googleapis.com/civicinfo/v2/elections?alt=json&prettyPrint=true'
class VoteSmartLocallyComponent extends React.Component<VoteSmartProps, VoteSmartState> {
    constructor(props) {
        super(props)
        console.log(props)
        this.state = {
            address: '',
            userAddressData: {}
        }
    }
    removeSpacesAddPluses() {
        return this.state.address.split(' ').join('+')      
    }
    lookupAddress(event: React.MouseEvent<HTMLButtonElement>) {
        event.preventDefault()
        const address = this.removeSpacesAddPluses()
        const fullRepURL = baseRepURL + address + endURL
        const fullElectionsURL = baseElectionsURL + address + endURL
        this.props.fetchAddressData(fullRepURL)
            /*
        store.subscribe(this.render)
        store.dispatch({
            type: 'LOOKUP_ADDRESS',
            payload: address
        })
             */
    }

    handleAddress(event: React.ChangeEvent<HTMLInputElement>) {
        event.preventDefault()
        const address = event.target.value
        this.setState({
            address: address 
        })
    }

    render() {
        return (
        <div>
            {console.log('log in the render method')}
            {console.log(this.state)}
            vote smart kids
            need to connect the redux and suff to make request
            <input 
                type='text' 
                placeholder='Address'
                onChange={ e => this.handleAddress(e) }
            />
            <button
                onClick={ e => this.lookupAddress(e) }
            >
            Submit for info
            </button>
        </div>
        )
    }

}

const mapStateToProps = (state) => {
    return {
        address: '',
        userAddressData: {}
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        fetchAddressData: (url) => dispatch(getAddressData(url))
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(VoteSmartLocallyComponent)
&#13;
&#13;
&#13;

我可以致电this.props.fetchAddressData(fullRepURL)来调用我的行动

// voteSmartActions.tsx

&#13;
&#13;
import {Action} from 'redux'
import store from '../store/store'
import axios from 'axios'

interface VoteSmartAction<Action> {
    type: string
    payload?: any
}
const getAddressData = (fullURL: string) => {
    return function(dispatch, getState) {
        if (fullURL !== '') { 
            return axios.get(fullURL).then(function (response) {
                dispatch(addressDataSuccess(response))
            
            }).catch(function (error) {
                  console.log(error)
            })
        }
    }
}
const addressDataSuccess = (addressData: any) => {
    return {
        type: 'HANDLE_RETURN_DATA',
        payload: addressData,
        addressData
    }
}
export {
    getAddressData, VoteSmartAction
}
&#13;
&#13;
&#13;

从那里到我的减速机

// voteSmartReducer.tsx

&#13;
&#13;
import {Action} from 'redux'
import {VoteSmartAction, getAddressData} from '../actions/voteSmartActions'
import axios from 'axios'
const INITIAL_STATE: any = {
    address: '',
    userAddressData: {}
}
const VoteSmartReducer = (state: any = INITIAL_STATE, action: VoteSmartAction<Action>): any => {
    switch(action.type) {

        case "HANDLE_RETURN_DATA":
            console.log("in reducer handling return payload is")
            const returnData = {
                ...state,
                userAddressData: action.payload 
            }
            console.log(returnData)
            
            return returnData

        default:
            return state
    }
}
export default VoteSmartReducer
&#13;
&#13;
&#13;

从那里我在reducer中创建的状态应该返回到我获取的数据的组件,但它不是。我要感谢任何建议或帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

目前,您正在传递userAddressData的空对象,并在mapStateToProps中传递address的空字符串。因此,您的组件将始终具有这些值。

您需要在mapStateToProps中指定,其中数据位于状态树中。

查看reducer的形状,查看数据在状态树中的位置,然后在mapStateToProps中以下列方式映射。

示例

index.js

import { combineReducers } from 'redux'
import voteSmartReducer from './VoteSmartReducer' // assuming this is in same directory
import someOtherReducer from './someOtherReducer' // example purposes

export default combineReducers({
    userAddressData: voteSmartReducer,
    otherExample: someOtherReducer
})

如您所见,voteSmartReducer返回的数据被映射到combineReducers中的关键userAddressData。所以state.userAddressData指向了这一点。这就是你将状态映射到道具的方式。

const mapStateToProps = (state) => {
    return {
        userAddressData: state.userAddressData,
        otherExample: state.otherExample
    }
}

创建商店时,从index.js导入reducer并将其作为第一个参数传递给createStore

实施例

import { createStore } from 'redux'
import reducers from './index.js'

const store = createStore(
        reducers
)