An old dev at my current company recently put his tail between his legs and fled after having to do Typescript/React, leaving me when a bunch of broken code.
My problem now is that I have this TypeScript code that simply removes an item from an array and changes the state:
var currentFiles = this.state.openFiles;
var index = this.state.openFiles.findIndex((f: IFileModel) => f.fileId == fileId)
currentFiles.splice(index, 1);
this.setState({
mode: "gallery",
openFiles: currentFiles
}, () => console.log(this.state.mode));
My problem is that the state never updates mode
, even though the setState should do so. Regardless of how I change things up, the console.log
shows is 0
.
Even putting a breakpoint in the render function, shows me that mode
is 0
, where it should be "gallery"
.
This is the initial state:
this.state = {
openFiles: [],
mode: "gallery",
categories: [],
galleryState: {}
}
Any advice?
You said in a comment that you've been left this code by a dev who recently left the company. I'm afraid they've left you with code breaking two of React's rules: :-)
You cannot directly modify state, including objects that this.state
refers to. You're doing that with currentFiles.splice(index, 1)
.
You're setting new state based on existing state, but not using the callback form of setState
.
To fix both (see comments):
// Use the callback form that receives the up-to-date state as a parameter.
this.setState(
({openFiles}) => {
var index = openFiles.findIndex((f: IFileModel) => f.fileId == fileId)
// (Do you need an `if (index !== -1)` check here?)
// Create a *new* array without the entry
var currentFiles = [...openFiles.slice(0, index), ...openFiles.slice(index+1)];
// Return the new state
return {
mode: "gallery",
openFiles: currentFiles
};
},
() => console.log(this.state.mode)
);
More in the state docs .
Live Example:
class Example extends React.Component { constructor(...args) { super(...args); this.removeFileOnClick = this.removeFileOnClick.bind(this); this.state = { mode: "main", openFiles: [ {fileId: 1, name: "File 1"}, {fileId: 2, name: "File 2"}, {fileId: 3, name: "File 3"}, {fileId: 4, name: "File 4"}, {fileId: 5, name: "File 5"} ] }; } removeFileOnClick(e) { const fileId = e.currentTarget.getAttribute("data-id"); this.setState( ({openFiles}) => { var index = openFiles.findIndex((f) => f.fileId == fileId) // (Do you need an `if (index !== -1)` check here?) // Create a *new* array without the entry var currentFiles = [...openFiles.slice(0, index), ...openFiles.slice(index+1)]; // Return the new state return { mode: "gallery", openFiles: currentFiles }; }, () => console.log(this.state.mode) ); } render() { return ( <div> Mode: {this.state.mode} <div> OpenFiles ({this.state.openFiles.length}): <div>{this.state.openFiles.map(file => <div><button data-id={file.fileId} onClick={this.removeFileOnClick}>X</button>{file.name}</div> )}</div> </div> </div> ); } } ReactDOM.render( <Example />, document.getElementById("root") );
<div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.2/umd/react-dom.production.min.js"></script>
Side note: If you don't like the double spread here:
var currentFiles = [...openFiles.slice(0, index), ...openFiles.slice(index+1)];
you can do it like this instead:
var currentFiles = openFiles.slice();
currentFiles.splice(index, 1);
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.