(React Redux) 整个状态重新启动并删除我添加新项目时所做的所有更改

问题描述

reducer 是这样的:

import {
    CREATE_COUNTRY,} from "../actions/actionConsts"

export const storeInitialState = {

    countries: [],otherThings: 0
}

export default function countriesReducer(prevstate = storeInitialState,action) {
    switch (action.type) {
        case CREATE_COUNTRY:
             return {
                ...prevstate,countries: [
                    ...prevstate.countries,action.country
                ]
            }

        default:
            return prevstate
    }
}

动作创建者是

export function createCountryActn(country) {
    return {
        type: CREATE_COUNTRY,country
    }
}

以及触发动作的组件


… … … … … 

    createTheCountry = (e) => {
        e.preventDefault()
        
        this.props.createCountry(this.state.name)

        this.setState({
            name: '',})
    }

… …… … … … 


每次添加新商品时,什么会导致商店的状态重新启动?

拉斐尔

解决方法

当时我不知道是什么导致了错误,但后来我发现了。

每次添加新项目时,一切都会重新启动,因为我调用创建新项目的函数的方式会丢失对 e(事件)的引用,所以当我执行时

e.preventDefault()

由于 e 没有正确的值,页面的默认行为实际上正在执行,并且是刷新。

我正在使用类组件,并且我将函数调用为:

onSubmit={this.createTheActivity}

它必须像

onSubmit={(e) => this.createTheActivity(e)}