簡體   English   中英

如何在redux中更新狀態

[英]How to update state in redux

我正在創建購物備忘錄。

我想獲得與 mapStateToProps 函數相關聯的最新 this.props。 但我得到的是與 mapStateToProps 函數相關聯的舊 this.props。

我嘗試定義 componentWillReceiveProps 函數,如下所示:

 componentWillReceiveProps(nextProps) {
        console.log(this.state.nextProps.createdVegetableList) //latest this.props
        this.setState({
            vegetableListsFromApiServer: nextProps.vegetableLists,
            createdVegetableList: nextProps.createdVegetableList
        });
       console.log(this.state.createdVegetableList) //undefined 
    }

如何獲取最新的this.props?

行動

export const postVegetableList = values => async dispatch => {
    const response = await axios.post("/api/vegetable_lists", values);
    dispatch({ type: CREATE_VEGETABLE_LIST, response });
};

減速器

import { CREATE_VEGETABLE_LIST } from "../actions";

export default (show = [], action) => {
    switch (action.type) {
        case CREATE_VEGETABLE_LIST:
            return {
                ...show,
                createdVegetableList: action.response.data.vegetableList
            };
};

蔬菜秀.js

import React, { Component } from "react";
import { Button, TextField } from "@material-ui/core";
import { connect } from "react-redux";
import {
    showVegetableList,
    postVegetableList,
    updateVegetableList,
    deleteVegetableList
} from "../actions";

class VegetableShow extends Component {
    constructor(props) {
        super(props);
        this.state = {
            vegetableList: "",
            vegetableListsFromApiServer: [],
            createdVegetableList: "",
        };
        this.onVegetableListChange = this.onVegetableListChange.bind(this);
        this.updateValue = this.updateValue.bind(this);
        this.showVegetable = this.showVegetable.bind(this);
        this.postVegetable = this.postVegetable.bind(this);
        this.updateVegetable = this.updateVegetable.bind(this);
        this.deleteVegetable = this.deleteVegetable.bind(this);
    }

    componentDidMount() {
        this.showVegetable();
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            vegetableListsFromApiServer: nextProps.vegetableLists,
            createdVegetableList: nextProps.createdVegetableList
        });
    }

    updateValue(e, idx) {
        e.persist();
        this.state.vegetableListsFromApiServer[idx].name = e.target.value;
        this.setState({
            vegetableListsFromApiServer: this.state.vegetableListsFromApiServer
        });
        const id = this.state.vegetableListsFromApiServer[idx].id;
        const name = e.target.value;
        this.updateVegetable(id, name);
    }

    onVegetableListChange(e) {
        this.setState({ vegetableList: e.target.value });
    }

    changeVegetableListField(e) {
        this.setState({ vegetableListsFromApiServer: e.target.value });
    }

    showVegetable() {
        const id = this.props.queryString;
        this.props.showVegetableList(id);
    }

    postVegetable() {
        const data = {};
        data.vegetableList = this.state.vegetableList;
        data.id = this.props.queryString;

        const response = axios.post("/api/vegetable_lists", data);
        response.then(res => {
            this.state.vegetableListsFromApiServer.push({
                name: res.data.vegetableList.name,
                id: res.data.vegetableList.id
            });
            this.setState({
                vegetableListsFromApiServer: this.state
                    .vegetableListsFromApiServer
            });
        });
        this.setState({
            vegetableList: ""
        });
        this.props.postVegetableList(data);
    }

    updateVegetable(id, name) {
        const data = {};
        data.id = id;
        data.name = name;
        this.props.updateVegetableList(data);
    }

    deleteVegetable(e, idx) {
        const id = e.currentTarget.dataset.vegetable;
        const newArray = this.state.vegetableListsFromApiServer;
        newArray.splice(idx, 1);
        this.setState({
            vegetableListsFromApiServer: newArray
        });
        this.props.deleteVegetableList(id);
    }

    renderShowVegetableList() {
        return this.state.vegetableListsFromApiServer.map(
            (vegetableList, idx) => (
                <React.Fragment key={vegetableList.id}>
                    <TextField
                        className="mt-5"
                        value={vegetableList.name}
                        onChange={e => this.updateValue(e, idx)}
                    />
                    <Button
                        className="mt-5 ml-3"
                        variant="contained"
                        color="secondary"
                        data-vegetable={vegetableList.id}
                        onClick={e => this.deleteVegetable(e, idx)}
                    >
                        delete
                    </Button>
                </React.Fragment>
            )
        );
    }

    render() {
        return (
            <div className="text-center">
                <h5 className="mt-5">vegetable list</h5>
                <TextField
                    className="mt-3"
                    value={this.state.vegetableList}
                    onChange={this.onVegetableListChange}
                />
                <Button
                    className="mt-3 ml-3"
                    variant="contained"
                    color="primary"
                    onClick={this.postVegetable}
                >
                    create
                </Button>
                {this.renderShowVegetableList()}
            </div>
        );
    }
}

const mapStateToProps = state => ({
    vegetableLists: state.show.vegetableLists,
    createdVegetableList: state.show.createdVegetableList,
});

const mapDispatchToProps = {
    showVegetableList,
    postVegetableList,
    updateVegetableList,
    deleteVegetableList
};

export default connect(mapStateToProps, mapDispatchToProps)(VegetableShow);

感謝您

您將本地狀態與全局狀態 (Redux) 混合在一起,將整個功能移動到 Redux 或本地狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM