Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我不能用api响应更新我的状态?数据是一个对象数组_Javascript_Reactjs_Api_State - Fatal编程技术网

Javascript 为什么我不能用api响应更新我的状态?数据是一个对象数组

Javascript 为什么我不能用api响应更新我的状态?数据是一个对象数组,javascript,reactjs,api,state,Javascript,Reactjs,Api,State,我有两个返回JSON对象的api请求。它们返回一个对象数组 我提出的一个API请求很好,允许我用响应更新状态,但另一个(下面)没有,我不明白为什么 获取流派列表的API请求: async getGenreList() { const genresResults = await getGenres(); return genresResults; } 请求: export const getGenres = async () => { try { con

我有两个返回JSON对象的api请求。它们返回一个对象数组

我提出的一个API请求很好,允许我用响应更新状态,但另一个(下面)没有,我不明白为什么

获取流派列表的API请求:

 async getGenreList() {
    const genresResults = await getGenres();
    return genresResults;
  }

请求:

export const getGenres = async () => {
  try {
    const response = await axios.get(
      "https://api.themoviedb.org/3/genre/movie/list?api_key=<APIKEY>&language=en-US"
    );
    const { genres } = response.data;
    return genres;
  } catch (error) {
    console.error(error);
  }
};

然后我想像这样更新
状态
,并将响应传递给
genreOptions
。但它告诉我
错误:对象作为React子对象无效(找到:具有键{id,name}的对象)。如果要呈现子对象集合,请改用数组。

   componentDidMount() {
    this.getGenreList().then((response) => {
      console.log(response)
      this.setState({ genreOptions: response});
    });
  }

当我更新状态并映射到它时,下面的代码可以工作,但我不想这样做,我想向下传递整个响应,这样我就可以映射到组件中的数据,因为我需要它来进行一些数据匹配

   this.setState({ genreOptions: response.map((genreOption) => {
        return genreOption.name
   })});

这是国家:

  this.state = {
      results: [],
      movieDetails: null,
      genreOptions: [],
      
    };
我想将这里的类型选项传递到
类型
,然后在
MovieResults
组件中映射到它

 <MovieResults>
          {totalCount > 0 && <TotalCounter>{totalCount} results</TotalCounter>}
          <MovieList movies={results || []} genres={genreOptions || []} />

        </MovieResults>


{totalCount>0&&{totalCount}results}
为什么我不能?有什么想法吗?我这样做是为了另一个类似的请求:S

更新以显示MOVIELIST组件

导出默认类MovieList扩展React.Component{
render(){
const{movies,tyres}=this.props;
const testFunction=(movieGenreIds)=>{
const matchMovieGenresAndGenreIds=genres.map((genreId)=>{
const matchedGenres=movieGenreIds.find((movieGenre)=>{
return movieGenre.id==genreId
})
return matchedGenres//返回匹配的对象
})
const result=matchMovieGenresAndGenreIds.filter(布尔值).map((el)=>{
返回el.name
})
返回结果
}
返回(
{movies.map((movie)=>{
常数{
标题
平均投票,
概述,
发布日期:,
发信人路,
类型识别码
}=电影;
返回(
);
})}
);
}
}
****电影项目组件***

export default class MovieItem extends React.Component {
  render() {
    const { title, overview, rating, release, poster, movieGenres } = this.props;
    return (
      // The MovieItemWrapper must be linked to the movie details popup
      <MovieItemWrapper>
        <LeftCont>
          <img
            className="movie-img"
            src={`https://image.tmdb.org/t/p/w500${poster}`}
          />
        </LeftCont>
        <RightCont>
         <div className="movie-title-container">
             <h2 className="movie-title">{title}</h2>
             <Rating>{rating}</Rating>
         </div>
             <div>{movieGenres}</div>
             <p>{overview}</p>
             <p>{release}</p>
        </RightCont>
      </MovieItemWrapper>
    );
  }
}
导出默认类MovieItem扩展React.Component{
render(){
const{title,overview,rating,release,poster,movieGenres}=this.props;
返回(
//MovieItemWrapper必须链接到电影详细信息弹出窗口
{title}
{评级}
{电影类型}
{概述}

{release}

); } }
请按照以下步骤修复代码。我会试着解释沿途发生的事情:

  • 在您的主要组件中。将状态设置为确实要传递给子组件的值。请记住,
    response
    将是一个对象数组
  • componentDidMount(){
    this.getGenreList()。然后((响应)=>{
    this.setState({genreOptions:response});
    });
    }
    
  • MovieList
    组件中。请检查您的
    testFunction
    ,以了解数据类型。下面的代码将返回一个字符串数组,其中包含电影流派数组中包含的流派名称
  • const testFunction=(movieGenreIds)=>{
    回归流派
    .filter((流派)=>{
    return movieGenreIds.includes(genre.id);
    })
    .map((流派)=>流派.name);
    };
    
  • 在您的
    MovieItem
    组件中。(这才是真正的问题所在)
  • 而不是:

    <div>{movieGenres}</div>
    

    还请注意,我添加了一个
    属性。只要有要渲染的元素列表,就应该这样做。有关这方面的更多信息,我将向您介绍。

    您的问题似乎出在
    MovieList
    组件中。你能把它的代码贴出来吗?特别是渲染部分。好的,我会发布,但是有点乱。在
    MovieList
    组件中,我想使用
    genres
    genreOptions
    并将
    genreOption
    id
    与另一个数组中的id进行比较-对于上下文,不要担心,继续。完成后,如果您需要更多关于我正在做什么的解释,请告诉我。非常感谢。好的,我或多或少了解您试图做什么,但我很抱歉地告诉您,现在问题似乎出在
    MovieItem
    组件中(我希望您最终尝试使用处理后的阵列)。我还看到了一些其他问题,但要完全回答,我需要你发布
    MovieItem
    code。非常感谢!好的,我学到的是,事实上我能够使用API请求的响应更新
    状态
    ,该请求是一个对象数组,但是我不能将API中的对象数组作为JSX表达式的结果。在您更正我的代码之前,我在
    ExpandableFilters
    中渲染
    {genre}
    ,它实际上是一个对象,因此无法工作,它给了我一个错误
    error:对象作为React子对象无效(找到:具有键{id,name}的对象)。如果要呈现子对象集合,请改用数组。
    export default class MovieItem extends React.Component {
      render() {
        const { title, overview, rating, release, poster, movieGenres } = this.props;
        return (
          // The MovieItemWrapper must be linked to the movie details popup
          <MovieItemWrapper>
            <LeftCont>
              <img
                className="movie-img"
                src={`https://image.tmdb.org/t/p/w500${poster}`}
              />
            </LeftCont>
            <RightCont>
             <div className="movie-title-container">
                 <h2 className="movie-title">{title}</h2>
                 <Rating>{rating}</Rating>
             </div>
                 <div>{movieGenres}</div>
                 <p>{overview}</p>
                 <p>{release}</p>
            </RightCont>
          </MovieItemWrapper>
        );
      }
    }
    
    <div>{movieGenres}</div>
    
    <div>{movieGenres.join(' ')}</div>
    
    <GenreFilterCont marginTop>
        {filtersShown && (
            <ExpandableFiltersUl>
                {this.props.movieGenres.map((genre, index) => {
                    return (
                        <ExpandableFiltersLi key={index}>
                            <Checkbox />
                            {genre.name}
                        </ExpandableFiltersLi>
                    );
                })}
            </ExpandableFiltersUl>
        )}
    </GenreFilterCont>