简体   繁体   English

React Custom Hook, Array 改为单入

[英]React Custom Hook, Array is changed to single entry

In my component, I need to set the value of an array from either the mockedList or from history.在我的组件中,我需要从 mockedList 或历史记录设置数组的值。 I created a custom hook for this requirement.我为此需求创建了一个自定义钩子。 In my custom hook I can see that the JSON data is an array but when I check the console log in render it only shows the first data, thus map function doesn't work.在我的自定义钩子中,我可以看到 JSON 数据是一个数组,但是当我在渲染中检查控制台日志时,它只显示第一个数据,因此 map 功能不起作用。 I removed the setting of history just to debug but got the same problem.我删除了历史设置只是为了调试,但遇到了同样的问题。 Please see my sample code below;请参阅下面的示例代码;

function Courses() {

    function useCourseData() {
        const history = useHistory();
        console.log(JSON.stringify(history));
        let courses = mockedCoursesList;
        /* Disabled for now 
        if (history.location.state && history.location.state.data) {
            console.log('getting from history');
            const courseList = [...mockedCoursesList];
            courses = courseList.push(history.location.state.data.course);
        }
        */
        //This logs the whole array
        console.log(JSON.stringify(courses));  
        return [courses];
    }

    const [filteredCourses, setFilteredCourses] = useCourseData();

    return (
        <div className='courses'>
            {/* The code below only log the first entry in the array instead of the whole array */}
            {console.log('Filtered: ' + JSON.stringify(filteredCourses))}
        

            {/* This throws an error since instead of array, filtereCourses is reduced to only one filteredCourse object */}
            {filteredCourses.map((course) => (
                <CourseCard
                    key={course.id}
                    course={course}
                    authors={authorNames(course.authors)}
                />
            ))}
        </div>
    );
}

export default Courses;

this line is creating problem.这条线正在制造问题。

courses = courseList.push(history.location.state.data.course);

/* array.push returns new length of an array, 
here you just push into cloned array and set this new array */

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

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