简体   繁体   English

为什么我在控制台中得到一个空数组和不正确的数据?

[英]Why am I getting an empty array and incorrect data fetching in console?

I have two buttons, the movies and tvshows button.我有两个按钮, moviestvshows按钮。 When I click on either I change the option to the opposite one as shown on the handleMovieClick and handleTVShowsClick methods.当我单击任一选项时,我将option更改为相反的选项,如handleMovieClickhandleTVShowsClick方法中所示。 Movies and TVshows may have the same id, that is why the option is important for fetching.电影和电视节目可能具有相同的 ID,这就是该option对于获取很重要的原因。

I am printing to the console.我正在打印到控制台。

(1) array of movie/tv ids (1) 电影/电视 ID array

(2) the option selected (2) 选择的option

(3) each individual object fetched based on the id and option (3) 根据idoption取出每个个体object

When I use the value to calculate the array of movie ids available the first time, I first get an empty array and then the expected result.当我第一次使用该value计算可用的电影 ID array时,我首先得到一个空数组,然后得到预期的结果。 That is the array of movie ids, option is movie and each individual promise objects is fulfilled.这是电影 ID 的array ,选项是电影,每个单独的 promise 对象都已实现。

Here's the kicker, when I click on the tvshows button, I am getting the following two things consoled.更重要的是,当我点击tvshows按钮时,我得到了以下两点安慰。

(1) same movie array of ids not updated, option changes to tv , however I get a bunch of promises with "status_message: "The resource you requested could not be found" because I am basically trying to retrieve promises with movie ids, but tvshow option. (1) 同一部电影的 id array未更新,选项更改为tv ,但是我得到了一堆带有“status_message:”The resource you requested could not be found”的承诺,因为我基本上是在尝试检索带有电影 id 的承诺,但是电视节目选项。

Then,然后,

(2) Then the result is changed and I everything as expected. (2) 然后结果改变了,我的一切都如预期的那样。 That is option stays the same, changed in above step, the array gets updated, and the individual promise objects are all fulfilled.那就是选项保持不变,在上面的步骤中发生了变化, array得到更新,并且各个 promise 对象都得到了满足。

What is happening?怎么了?

I get that it is happening because of the code in my JSX where I am making use of the array ids.我知道这是因为我在 JSX 中使用array id 的代码。 I think I need to only call the array.map() part after the useEffect has run and the so array is updated but how to do this and why is useEffect not running the first time?我想我只需要在 useEffect 运行并且 so 数组更新后调用array.map()部分,但是如何执行此操作以及为什么 useEffect 不是第一次运行?

Here is the code.这是代码。


const Results = () => {

    const options = ['movie', 'tv']; 
    const { value } = useParams(); // from router 
    const [ page, setPage ] = useState(1);
    const [ option, setOption ] = useState(options[0]);
    const [ array, setArray ] = useState([]);

    const handleMovieClick = () => {setOption('movie')}
    const handleTVShowClick = () => {setOption('tv')}

    useEffect(() => {
        console.log('HERE');
        fetchArrayByPage(value, page, option).then(res => setArray(res));
    }, [value, page, option])

    console.log(array);
    console.log(option);

    return (
        <div className="results-container">
            <div>
                <ul className='categories'>
                    <button onClick={handleMovieClick}>Movies<span>{0}</span></button>
                    <button onClick={handleTVShowClick}>TV Shows<span>{0}</span></button>
                </ul>
            </div>
            {
            <div>
                <div className='results-list'>
                    {array.map((arr, index) => {
                        console.log(fetchID(arr, option));
                        return <Card key={index} id={arr} option={option}></Card>})}
                </div>

                <div className='pages'>

                </div>
            </div>
            }
        </div>
    );
}

useEffect 's callback is fired after the render and fetchArrayByPage seems to be async. useEffect的回调在渲染后触发,并且fetchArrayByPage似乎是异步的。 So clicking on "TV shows" results in:所以点击“电视节目”会导致:

  1. option is changed to "tv" ( array stays the same) option更改为“电视”( array保持不变)
  2. console.log(array); console.log(option);
  3. render with new option and old array使用新option和旧array渲染
  4. console.log('HERE'); fetchArrayByPage(...)
  5. some time passes一段时间过去了
  6. setArray(res)
  7. render with new option and new array使用新option和新array渲染

You should call fetchArrayByPage from your handle*Click handlers:您应该从handle*Click处理程序中调用fetchArrayByPage

const handleTVShowClick = () => {
    fetchArrayByPage(value, page, "tv").then(res => {
        setOption('tv');
        setArray(res);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM