【问题标题】:How to update state array?如何更新状态数组?
【发布时间】:2020-03-10 05:40:08
【问题描述】:

我正在用 Reactjs 制作一个应用程序。在其中,我有一个 API,它从 AWS 数据库表中获取数据并填充一个状态数组,然后再填充一个表。 我不知道如何让用户依次更新表的值,然后保存这些更改并让 API 将其上传回数据库。 我有一个更新方法,但它给出了一个错误,说我无法更新状态数组或者会抱怨列数组未定义。

我有以下代码:

export default function Complaints(props) {

    const [complaint, setComplaint] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [isInEditMode, setIsEditMode] = useState(false);
    const [defaultValue, setDefaultValue] = useState("");

    var columsArr = [
        { title: 'Customer ID', field: 'id' },
        { title: 'Issue', field: 'complaintName' },
        { title: 'Description', field: 'complaintDescription'},
        { title: 'Order ID', field: 'complaintOrderId'},
        { title: 'Submitted', field: 'createdAt'},
        { title: 'Updated', field: 'updatedAt'},
        { title: 'Admin Comment', field: 'adminComment'},
    ];

    useEffect(() => {
        async function onLoad() {
            if (!props.isAuthenticated) {
                return;
            }

            try {
                const complaint = await loadComplaint();
                setComplaint(complaint);
                setState({
                    columns: [state.columns, ...columsArr],
                    complaint: [...state.complaint, ...complaint]
                });
                console.log(complaint)
            } catch (e) {
                alert(e);
            }

            setIsLoading(false);
        }

        onLoad();
    }, [props.isAuthenticated]);

    function loadComplaint() {
        return API.get("kleen", "/Complaint");
    }

    // function edit(adminComment) {
    //     setIsEditMode(true);
    //     setDefaultValue(adminComment);
    //     console.log("value is"+ adminComment);
    // }

    // function updateComplaint() {
    //     return API.put("kleen", `/Complaint/${props.}`);
    // }

    const [state, setState] = React.useState({
        columns: [],
        complaint: []
});

    return (
        <MaterialTable style={{
            marginTop: "8rem",
            marginLeft: "auto",
            marginRight: "auto",
            position: "sticky",
        }}
            title="Complaints"
            columns={state.columns}
            data={state.complaint}
            editable={{
                onRowUpdate: (newData, oldData) =>
                    new Promise(resolve => {
                        setTimeout(() => {
                            resolve();
                            if (oldData) {
                                let key = 1;
                                setState(prevState => {
                                    complaint: prevState.complaint.map(el => el.key === key ? {...el, adminComment: "testing"}: el)
                                    // const data = [...prevState.data];
                                    // data[data.indexOf(oldData)] = newData;
                                    // return { ...prevState, data };
                                });
                            }
                        }, 600);
                    }),
            }}
        />
    );
}

我是 Reactjs 的新手,任何帮助将不胜感激。

【问题讨论】:

    标签: javascript arrays reactjs state material-table


    【解决方案1】:

    如果你想使用状态,那么最好使用组件类

    export default class Complaints extends Component {
    
    //assign initial value to state
    state={
        propsObj : this.props
    }
    
    
    ...
    }
    

    如果你想使用组件,你必须导入它

    import React, { Component } from "react";
    

    在组件类中你必须使用this.props 而不是props

    稍后如果您想更改状态,只需使用this.setState({ propsObj: 'some thing new'});

    【讨论】:

      【解决方案2】:

      您可以实现的一种方法是:

      1. 首先将状态存储在一个变量中
      2. 更新数组变量
      3. 将变量恢复到状态。

      【讨论】:

      • 更新状态是否会自动使用更新后的数据重新渲染表格?另外我正在使用 MaterialTable,我怎样才能让它只更新已更改的数组值?
      猜你喜欢
      • 2021-06-07
      • 2021-06-10
      • 2021-01-14
      • 2018-05-21
      • 2019-06-03
      • 2021-10-23
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      相关资源
      最近更新 更多