ReactJS表格评分输入框无法编辑,需实现点击更新修改数组值
Fixing the Editable Rating Input and Update Function in Your React Class Component
Let's walk through the issues in your code and fix them so the rating input works as expected and updates your state properly.
Key Problems in Your Current Code
- You're mutating state directly: When you do
movie.rating = event.target.value, you're modifying the state object directly instead of creating a new copy. React doesn't detect this change, so the input doesn't re-render with the new value. - Update button isn't passing the movie data: Your button's
onClickdoesn't send the current movie to theupdateRatingfunction, so you can't target the right movie to update. - No state update in
updateRating: Right now, you're just showing an alert instead of actually updating themovieDetailsarray in state.
Fixed Code Implementation
import React, { Component } from 'react'; export class UpdateMovie extends Component { state = { movieDetails: [ { "id": 9001, "name": "Dead Pool", "rating": 8.0 }, { "id": 9002, "name": "The Emoji Movie", "rating": 1.5 }, { "id": 9003, "name": "Dunkirk", "rating": 8.5 } ], errorMessage: "", successMessage: "", buttonActive: false } updateRating = (movieToUpdate) => { const confirmation = window.confirm(`Do you want to update rating to: ${movieToUpdate.rating}?`); if (confirmation) { // Create a new array with the updated movie (immutable update) const updatedMovies = this.state.movieDetails.map(movie => movie.id === movieToUpdate.id ? { ...movie } : movie ); this.setState({ movieDetails: updatedMovies, successMessage: "Rating updated successfully!", errorMessage: "" }); // Clear success message after 3 seconds setTimeout(() => this.setState({ successMessage: "" }), 3000); } else { this.setState({ errorMessage: "Update cancelled.", successMessage: "" }); setTimeout(() => this.setState({ errorMessage: "" }), 3000); } } handleChange = (event, movie) => { // Create a new movie object with the updated rating const updatedMovie = { ...movie, rating: parseFloat(event.target.value) }; // Update the state with a new array containing the modified movie this.setState(prevState => ({ movieDetails: prevState.movieDetails.map(m => m.id === movie.id ? updatedMovie : m ) })); }; getMovieDetails = () => { return this.state.movieDetails.map((movie) => { return ( <tr key={movie.id}> <td>{movie.id}</td> <td>{movie.name}</td> <td> <input type="number" step="0.1" name={`rating-${movie.id}`} value={movie.rating} onChange={(event) => this.handleChange(event, movie)} /> </td> <td> {/* Pass the current movie to updateRating */} <button onClick={() => this.updateRating(movie)}> Update </button> </td> </tr> ) }) } render() { return ( <div className="row "> <div className="col-md-6 offset-md-3 "> <br></br> <h1 className="text-center">Update Rating</h1> {/* Display success/error messages */} {this.state.successMessage && <div className="alert alert-success">{this.state.successMessage}</div>} {this.state.errorMessage && <div className="alert alert-danger">{this.state.errorMessage}</div>} <table id="movies" className="table table-striped"> <thead> <tr> <th>Movie Id</th> <th>Movie Name</th> <th>Rating</th> <th>Action</th> </tr> </thead> <tbody> {this.getMovieDetails()} </tbody> </table> </div> </div> ) } } export default UpdateMovie;
Key Changes Explained
Immutable State Updates:
- In
handleChange, we create a newupdatedMovieobject using the spread operator ({ ...movie }) instead of modifying the original state object. Then we map over themovieDetailsarray to replace the old movie with the updated one, creating a new array for state. - In
updateRating, we do the same immutable update to ensure React detects the state change and re-renders the component.
- In
Passing Movie Data to Update Button:
- We changed the button's
onClickto() => this.updateRating(movie)so the function receives the specific movie we want to update.
- We changed the button's
Improved Input Type:
- Switched the input to
type="number"withstep="0.1"to make it easier to enter valid rating values (instead of free text).
- Switched the input to
User Feedback:
- Added success/error messages that auto-dismiss after 3 seconds to let the user know the result of their update action.
内容的提问来源于stack exchange,提问作者chandan kumar
相关产品推荐
相关产品推荐

