我仍然对react和react挂钩感到困惑。我正在研究Link处的这种反应性挑战。首次加载代码时,我的文章状态未显示正确的数据。如果您在控制台日志中查看,则我的文章状态显示为空数组,然后是正确的数据,但是在我的代码首次呈现时我需要正确的数据,否则我的代码将无法正确执行。它说我不能映射未定义的。我的代码有什么问题?
import React, {useState, useEffect} from 'react';
const Articles = () => {
const [article, setArticle] = useState([])
const [page, setPage] = useState(1)
useEffect(() => {
fetch(`https://jsonmock.hackerrank.com/api/articles?page=${page}`)
.then(res => res.json())
.then(data => setArticle(data))
}, [page])
const pgNums = Array(article.total_pages).fill().map((_, i) => i + 1)
console.log(article)
return (
<React.Fragment>
<div className="pagination">
{pgNums.map(n => <button data-testid="page-button" key={n} onClick={() => setPage(n)}>{n}</button>)}
</div>
<ul className="results">
{/* {article.data.map(article => <li key="title-1" data-testid="result-row">{article.title}</li>)} */}
</ul>
</React.Fragment>
);
}
export default Articles;
答案 0 :(得分:0)
问题是当您尝试访问suspend fun searchWithRanks(query: String): List<Person> {
return personDao.search(query)
.sortedByDescending { result -> rank(result.matchInfo.skip(4)) }
.map { result -> result.person }
}
时不可用。由于import random
import tkinter as tk
import time
import sys
import datetime
import os
window = tk.Tk()
window.title("Shanes Number Guessing Game")
#window.geometry("600x500")
window.configure(bg='#74eb34')
# GUI Image
#logo = tk.PhotoImage(file="C:\Python-Tkinter pics\\numberguess.png")
#photo1 = tk.Label(image=logo)
#photo1.image = logo
#photo1.pack()
# score
tries = 0
wins = 0
# user enters their username
userNameLabel = tk.Label(window, text="please enter your name below", bg='#74eb34', font='bold')
userNameEntry = tk.Entry(window)
name = str(userNameEntry.get())
userNameLabel.pack()
userNameEntry.pack()
def HiName():
HiNameLabel = tk.Label(window,text="Gday " + str(userNameEntry.get()) + "\n" + "I want to play a game" + "\n" + "roll the dice to get a number" + "\n" + "The computer will then guess a number between 1-100" + "\n" + "your dice number determines how many guesses you get" + "\n" + "lets play" , bg='#74eb34')
HiNameLabel.pack()
HiNameButton = tk.Button(window,text="record name", command=HiName)
HiNameButton.pack()
# User enters their guess in a entry box
enterGuessLabel = tk.Label(window, text="enter guess below", bg='#74eb34', font='bold')
enterGuessLabel.pack()
enterGuess = tk.Entry(window, text=0)
enterGuess.pack()
diceResult = random.randrange(1, 6)
# Throw dice
def throwDice():
global diceResult
global tries
print(diceResult)
diceLabel = tk.Label(window, text="the number of your dice is: " + str(diceResult),font="bold", bg='#74eb34')
diceLabel.pack()
tries += diceResult
def takeGuess():
global wins
global losses
global tries
global diceResult
global rannum
count = diceResult
userGuess = int(enterGuess.get())
while not count == 0:
print(rannum)
if userGuess == rannum:
rannum = random.randrange(1, 100)
print("correct")
wins += 1
correctLabel = tk.Label(window,text="correct")
correctLabel.pack()
break
elif userGuess < rannum:
print("incorrect, you guessed to low")
rannum = random.randrange(1, 100)
print(count - 1)
print("the number was:", (rannum))
incorrectLabel = tk.Label(window, text="incorrect, you guessed to low ")
lb = tk.Label(window, text = rannum).pack()
incorrectLabel.pack()
tries += 1
count -= 1
break
elif userGuess > rannum:
print("incorrect, you guessed to high")
rannum = random.randrange(1, 100)
print(count - 1)
print("the number was: ", (rannum))
incorrectLabel = tk.Label(window, text="incorrect, you guessed to high ")
lbd = tk.Label(window, text = rannum).pack()
incorrectLabel.pack()
tries += 1
count -= 1
break
# GUI Buttons
diceButton = tk.Button(window, text="roll dice", command=throwDice)
diceButton.pack()
guessButton = tk.Button(window, text="take guess", command=takeGuess)
inputGuess = guessButton
guessButton.pack()
rannum = random.randrange(1, 100)
# Timestamp
timestamp = time.strftime("%B %d, %Y %H:%M:%S")
print(timestamp)
# open file
def file():
os.system("statistics.txt")
def saveStats():
with open("statistics.txt", "a") as output:
output.write(str(userNameEntry.get()) + " played a game on: " + time.strftime("%H:%M:%S %Y-%m-%d") + " and got the results: " + "\n")
saveButton = tk.Button(window,text="Save Stats", command=saveStats)
saveButton.pack()
fileButton = tk.Button(window, text="open file", command=file)
fileButton.pack()
window.mainloop()
的调用。您可以定义另一个状态article
,该状态在获取数据时显示加载程序;如果数据不可用,则asynchronous api
不显示任何内容。
在您的情况下,您可以这样做:
loading
答案 1 :(得分:0)
每次调用API的页面更改时,都应使用此条件渲染。您应该返回loading component / waitIndicator等,而不是null
const Articles = () => {
const [article, setArticle] = useState([])
const [page, setPage] = useState(1)
const [pgNums, setPageNums] = useState([])
useEffect(() => {
fetch(`https://jsonmock.hackerrank.com/api/articles?page=${page}`)
.then(res => res.json())
.then(data => {
console.log(data.data);
setArticle(data.data)
setPageNums(Array(data.total_pages).fill().map((_, i) => i + 1))
}
)
}, [page])
return (
<React.Fragment>
<div className="pagination">
{pgNums.length > 0 ? pgNums.map(n => <button data-testid="page-button" key={n} onClick={() => setPage(n)}>{n}</button>) : null}
</div>
<ul className="results">
{article.length > 0 ? article.map((article,i) => <li key={i} data-tes.tid="result-row">{article.title}</li>) : null}
</ul>
</React.Fragment>
);
}