繁体   English   中英

值显示 2 次并且

[英]Value is being displayed 2 times and .map function not working - Reactjs

  1. 为什么我的待办事项数据第一次没有显示值但第二次显示以及为什么显示 2 次控制台图像
   const [todos, setTodos] = useState([])
    
    useEffect(() => {
        todolist()
        
    },[])

    const todolist = () => {
        if (typeof window !== undefined) {
            if (localStorage.getItem("jwt")) {
                let temp = JSON.parse(localStorage.getItem("jwt"));
                
                getToDo(temp.user._id, temp.token).then(response => {
                   
                    setTodos(response)
                }).catch((err) => {
                    console.log(err)
                })
            }
        }
    }

    const getToData = () => {
       
        console.log('todo', todos.todos)
      
    }

2.当我申请时。map function 我收到错误TypeError: Cannot read property 'map' of undefined

const getToData = () => {
       
        console.log('todo', todos.todos)

        let userTodos = todos.todos
        //here is where i get error
        return userTodos.map((current, index) => {
            return <Todo todo={current} key={index} />
        })
    }

你能帮我解决这两个问题吗

todos是 object,而不是数组。 因此,您需要将其初始化如下:

const [todos, setTodos] = useState({})

并且调用端点是异步的,因此在端点调用进行时您将获得空值。 因此,您需要设置todos.todos的后备,以避免出现undefined的值,如下所示:

const userTodos = todos.todos || []

这应该可以解决您的问题。 享受!

渲染组件后调用useEffect挂钩。 因此,当您的组件第一次渲染时,它将显示空记录,然后调用 useEffect 并且您正在设置setState ,它将触发重新渲染组件(反应默认行为)。

所以为了避免错误,你可以得到这样的值

let userTodos = todos ? todos.todos : []

或通过解构

let { todos: userTodos = []} = todos;

希望这会帮助你。

userTodos.map给出错误,因为userTodostodos.todos ,在第一次渲染时undefined

React 正在渲染所有内容,然后运行加载数据的useEffect ,然后使用新的 state 重新渲染。

因此,您需要处理初始 state,其中todos[] ,因此您不能在maptodos.todos ,因为它不存在。

有两种方法可以解决此问题:

  1. 您可以在渲染方法的顶部检查todos.todos === undefined是否为空,如果它为空,则可以选择渲染"loading..."

  2. 您可以更改您的 state 以便您没有todo.todos但待办事项列表直接在根 state 列表上,这样您就可以map列表,防止它出现空错误。 通过在 useEffect 中执行setTodos(response.todos)来做到这一点。

我建议同时执行上述两项操作,因为如果连接速度较慢,用户可以看到正在加载的内容,并且您的 state 将被正确格式化,以便将来出现此类错误的可能性较小。

我理解第二个问题:

const getToData = () => {
 
   console.log('todo', todos.todos)

   let userTodos = todos ? todos.todos : [];
   //here is where i get error
   return userTodos.map((current, index) => {
      return <Todo todo={current} key={index} />
   })
}

希望它会有所帮助。

暂无
暂无

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

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