简体   繁体   中英

How to fix: Error: Actions must be plain objects. Use custom middleware for async actions.?

I'm making ReactApp, and when i try to write something in Input, i have this error, and i have no idea how to solve this... Can anybody help me? And also explaine me how to make rigth dispatch in this situation.


API request

export const searchWeather = value => {
    Axios.get(`${API.base}weather?q=${value}&units=metric&APPID=${API.key}`)
    .then(res => res.json())
    .then(response => {
        console.log(response)
    })
}

Reducer

export const getCurrentWeather = () => {
    return (dispatch) => {
        let value = initialState.cityValue

        dispatch(loader(true))
        dispatch(searchWeather(value))
        dispatch(loader(false))
    } 
}

Container

class NavContainer extends React.Component {
    componentDidMount(){
        getCurrentWeather()
    }

    render(){
        return (
            <NavBar {...this.props} />
        )
    }
}

const mapStateToProps = state => ({
    cityValue: state.weatherReducer.cityValue
})

export default connect(mapStateToProps, {getCityValue,getCurrentWeather})(NavContainer)

Component

const NavBar = ({cityValue,getCityValue,getCurrentWeather}) => {

    return(
        <div className="row">
            <div className='col-lg-4 nav-bar-mobile' >
                <ul>
                    <li >Home</li>
                    <li>Weather</li>
                    <li>Contact</li>
                </ul>
            </div>
            <div className='col-lg-8 search-bar'>
                <input onKeyPress={getCurrentWeather} value={cityValue} onChange={e => getCityValue(e.target.value)} placeholder='Search Location...'/>
            </div>
            <div className='col-lg-4 nav-bar' >
                <ul>
                    <li >Home</li>
                    <li>Weather</li>
                    <li>Contact</li>
                </ul>
            </div>
        </div>
    )
}

You should use some middleware, for example redux-thunk. You should create thunk looks like

const searchWeather = data => dispatch => {
    searchWeatherAxiosRequest(data)}

And then use this thunk in component on handle click:

 searchWeather()

Also you shouldn't dispatch something in Reducer. Reducer should just change the state

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM