状态更新后无法更新组件

时间:2019-05-07 20:37:59

标签: reactjs

我正在使用ReactTable渲染表。

export class ItemHandler extends React.Component<IitemsProps, IitemState> {
    constructor(props: IitemsProps) {
        super(props);

        this.state = {
            items: [], 
            columns: [
                { Header: 'Name', accessor: 'Name', sortable: true },
                { Header: 'ID', accessor: 'ID', sortable: true }
            ],
            selectedRow: {} as Iitem,
            isLoaded: false,
            Item: {} as Iitem
          }

          this._saveNewItem = this._saveNewItem.bind(this);
          this.onFieldChange = this.onFieldChange.bind(this);
    }
    public componentDidMount(): void {
        // Code for fetching data...
    }
    render() {
        const {items, columns, selectedRow } = this.state;

        return(
            <div>
                <CommandButton
                    data-automation-id="addItem"
                    iconProps={{ iconName: 'AddTo' }}
                    text="Add new item"
                    onClick={this.createNewItemDialog}
                />

                <ReactTable 
                    data={items}
                    columns={columns}
                    defaultPageSize={items.length}
                    resizable={false}
                    loading={false}
                    showPagination={false}
                    showPaginationTop={false}
                    showPaginationBottom={false}
                    showPageSizeOptions={false}
                />

                <Dialog
                    hidden={this.state.hideCreateNewItemDialog}
                    >
                    <CreateNewDialogContent 
                        selectedRow={selectedRow}
                        saveNewItem={this._saveNewItem} 
                        />
                </Dialog>
            </div>
        )
    }

    private _saveNewItem = (selectedRow:Iitem) => {

        //selectedRow comes from CreateNewDialogComponent
        const updatedItem = selectedRow;
        updatedItem.Name = selectedRow.Name;
        updatedItem.ID = selectedRow.ID;

           fetch(`${remoteWebLocation.origin}/api/tblName${remoteWebLocation.search}`, {
                method: 'POST',
                credentials: 'include',
                headers: new Headers({
                    "Content-Type": "application/json",
                    Accept: "application/json"
                }),
                body: JSON.stringify(this.state.Item)
            })
            .then(response => {
                if (response.ok) {

                    const newData = this.state.items;

                    newData.push({
                        Name: updatedItem.Name,
                        ID: updatedItem.ID
                    })

                    this.setState({
                        items:newData
                    });
                }
            });
        });
    }
}

在我的子组件中:

export class CreateNewDialogContent extends React.Component<IDialogProps, IDialogState> {
constructor(props: IDialogProps) {
    super(props)
    this.state = {}
}
render() {
    let selectedRow = this.props.selectedRow;

    return (
    <div>
        <DialogContent>
            <TextField 
                required
                label="Name" 
                value={selectedRow.Name}
            />
            <TextField 
                required
                label="ID" 
                value={selectedRow.ID} 
            />
        </DialogContent>
        <DialogFooter>
            <PrimaryButton 
                onClick={() => this.saveNewItem(selectedRow)} 
                disabled={_disabled} 
                text="Save" 
            />
        </DialogFooter>
    </div>
    )
}

private saveNewItem = (selectedRow:IItem) => {

    //This sends selectedRow to parent function saveNewItem.
    this.props.saveNewItem(selectedRow);

}
}

当我在_saveNewLanguage中调试时(在父组件中),我可以看到正确的值,而在执行POST时,我可以看到状态更新(通过push)并添加新值,但是该表可以无法更新。

我已经尝试过许多关于stackoverflow的解决方案,但是没有成功。谁能看到它为什么不更新?

谢谢。

更新

我尝试创建一个简单的Component而不是ReactTable来渲染项目,并且工作正常。因此,ReactTable似乎是一个问题。

1 个答案:

答案 0 :(得分:1)

您正在改变状态,这很糟糕。即使新项目已添加到数组中,它仍然是相同的 array实例。当这传递到您的表时,oldTable === newTable将为真。您的状态应该是不可变的,这意味着您应该始终返回一个新的对象或数组,而不是对其进行适当的突变。对于数组,您可以将它们分散到新数组中,并在末尾添加新项。在您的_saveNewItem方法中是这样的:

// after the fetch()
.then(response => {
    if (response.ok) {
        this.setState(state => ({
            items: [
                ...state.items,
                {
                    Name: updatedItem.Name,
                    ID: updatedItem.ID
                }
            ]
        }));
    }
});