使用Redux和useDispatch将基于类的组件重构为功能组件不起作用

时间:2020-06-19 17:55:32

标签: reactjs react-redux react-hooks

我正在尝试学习useDispatch以重新制造类组件。调度有时在起作用,但其他方面却没有。请让我知道我在做什么错...

dev-tools: what redux dev tools says

组件:

import React, { useState, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';

import {
    hideAllComps,
    newSearchLocation,
    logFullSearchName,
} from '../../../../actions';

function SearchBar() {

    const dispatch = useDispatch();
    const hideAllCompsState = useSelector((state) => state.hideOrShow);
    const currentLocation = useSelector((state) => state.location);
    const searchedLocation = useSelector((state) => state.searchedLocation);

....


function logNewSearchLocation(response) {
        dispatch(newSearchLocation(response));
        console.log(searchedLocation); // logs 'none'
    }

    function searchLocation(city) {
        let key = `XXX`;
        let coord = ['lat', 'lon'];
        let site = `XXX`;
        axios
            .get(site)
            .then((response) => {
                console.log(response); // results are there
                logNewSearchLocation(response);
            })
            .catch((err) => {
                alert(err);
            });
    }

我的动作:

export const newSearchLocation = (loc) => {
    return {
        type: 'NEW_SEARCH_LOCATION',
        payload: loc,
    };
};


我的减速器:

import { combineReducers } from 'redux';

...

const searchedLocation = (loc = 'none', action) => {
    if (action.type === 'NEW_SEARCH_LOCATION') {
        return action.payload;
    } else {
        return loc;
    }
};

....
const weatherApp = combineReducers({
    ...
    searchedLocation: searchedLocation,
    ...
});

export default weatherApp;

使用mapStateToProps等在基于类的组件中与Redux一起正常工作。我想学习脱离基于课堂的知识,陷入困境。我非常感谢您的帮助...

0 个答案:

没有答案