[英]Value is being displayed 2 times and .map function not working - Reactjs
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
給出錯誤,因為userTodos
是todos.todos
,在第一次渲染時undefined
。
React 正在渲染所有內容,然后運行加載數據的useEffect
,然后使用新的 state 重新渲染。
因此,您需要處理初始 state,其中todos
是[]
,因此您不能在map
上todos.todos
,因為它不存在。
有兩種方法可以解決此問題:
您可以在渲染方法的頂部檢查todos.todos === undefined
是否為空,如果它為空,則可以選擇渲染"loading..."
。
您可以更改您的 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.