【问题标题】:Attempting to set the state of an array in ReactJS but not sure how to map over尝试在 ReactJS 中设置数组的状态,但不确定如何映射
【发布时间】:2020-08-20 19:01:08
【问题描述】:

所以我正在尝试为我和我的朋友创建一个电影投票应用程序。我在 react 中设置了大部分应用程序,但我不知道如何设置/更新“评级”对象的状态。

数组设置如下:

import React, { useState, createContext } from 'react';

export const MovieListContext = createContext();

export const MovieListProvider = (props) => {
    const [movieList, setMovieList] = useState([
        {
            name: "Test",
            rating: ""
        },
        {
            name: "Testing",
            rating: ""
        },
        {
            name: "Tester",
            rating: ""
        },
    ]);
    return (
        <MovieListContext.Provider value={[movieList, setMovieList]}>
            {props.children}
        </MovieListContext.Provider>
    )
}

然后我希望能够覆盖数组并使用我们的每个评级更新评级对象

import React, { useState, useContext } from 'react';
import Movie from './Movie'
import {MovieListContext} from "../MovieListContext";
import VotingCandidates from "./VotingCandidates";

const VotingForm = () => {
    const [movieList, setMovieList] = useContext(MovieListContext);
    
    const handleRatingChange = (e, movieList) => {
        setMovieList([...movieList, {rating: e.target.value}]);
        console.log(movieList)
    }

    return (
        <div>
            {movieList.map(movieList => (
                <li key={movieList.name}>{movieList.name}
                <input onChange={handleRatingChange} type="text"/>
                </li>
                
            ))}

            
            <button>VOTE</button>
        </div>
    )
}

export default VotingForm

我想不出办法让movieList.rating 对象的状态能够更新

【问题讨论】:

标签: javascript arrays reactjs


【解决方案1】:

为了更新数组中的特定项,您需要知道要更新哪个元素。为此,您将需要一些东西来区分。在您的情况下,您可以使用名称,但唯一的 id 或项目的索引会更好。然后,将其传递给偶数处理程序。

我个人会这样做:

  1. 将数组更改为具有 id 的
[
  { id: 1, name: "Test"},
  { id: 2, name: "Foo"}
]
  1. 在 jsx 中映射数组并将正确的数据传递给事件处理程序:
{movieList.map(item => (
  <li key={movieList.id}><input onChange={() => handleRatingChange(item, movieList)} /></li>
))}
  1. 更新事件处理程序以更新状态
const handleRatingChange = (e, updatedItemId, movieList) => {
  setMovieList(movieList.map(item => {
    if(item.id == updatedItemId) {
      return {...item, rating: e.currentTarget.value}
    }
    return item
  }) 
}

【讨论】:

  • 所以我稍微更新了我的代码,现在我收到以下错误:TypeError: Cannot read property 'map' of undefined
  • @TeflonTrout 你能发布你的代码吗?该错误指出,此时您要映射的任何内容都未定义或未知,因此您传递给函数的内容可能是错误的,或者是拼写错误?很难说。另外,顺便说一句:为什么不只使用 React 组件内部的状态?
猜你喜欢
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-14
  • 2022-07-07
  • 2018-10-21
  • 2020-02-22
相关资源
最近更新 更多