我有一个带有帖子的上下文 API。当我转到其他页面时,这些 API 不起作用。
当我尝试调用 words.length
时,它起作用了。如何访问 words
对象的属性?
上下文API:
export const WordContext = createContext();
const WordContextProvider = (props) => {
const [words, setWords] = useState([]);
axios.defaults.baseURL = "http://localhost:3002";
const fetchData = async () => {
const response = await axios.get("/words");
if (response !== null) {
setWords(response.data);
}
};
useEffect(() => {
fetchData();
}, []);
return (
<WordContext.Provider value={{ words, addWord, deleteWord, updateWord }}>
{props.children}
</WordContext.Provider>
);
};
export default WordContextProvider;
App.js:
import WordContextProvider from "./contexts/WordContext";
.
.
.
<Route
path="/quiz"
render={() => (
<WordContextProvider>
<Quiz />
</WordContextProvider>
)}
/>
测验页面:
const Quiz = () => {
const { words } = useContext(WordContext);
const [currentQuestion, setCurrentQuestion] = useState(0);
const [trueScore, setTrueScore] = useState(0);
const [falseScore, setFalseScore] = useState(0);
const handleAnswerClick = (e) => {
e.preventDefault();
const nextQuestion = currentQuestion + 1;
setCurrentQuestion(nextQuestion);
const counterTrue = trueScore + 1;
setTrueScore(counterTrue);
const counterFalse = falseScore + 1;
setFalseScore(counterFalse);
};
return (
<Form onSubmit={handleAnswerClick}>
<Row className="justify-content-between mt-5 mb-5">
<Col xs md={2} className="text-center">
<FaCheckCircle
icon="check-circle"
className="text-success display-2"
/>
<h1 className="mt-3">{trueScore}</h1>
</Col>
<Col xs md={2} className="text-center">
<FaTimesCircle
icon="times-circle"
className="text-danger display-2"
/>
<h1 className="mt-3">{falseScore}</h1>
</Col>
</Row>
<Row className="d-flex justify-content-center align-items-center flex-column">
<Col md={12} lg={6} className="text-center">
<h2 className="fs-1 text-danger mb-5">{words[0].foreign}</h2>
</Col>
<Col md={12} lg={6} className="text-center">
<h2 className="fs-1 text-danger mb-5">{words[0].native}</h2>
</Col>
<Button type="submit" variant="info" className="px-5 py-3 mt-5">
Apply
</Button>
</Row>
</Form>
);
}
export default Quiz;
答案 0 :(得分:1)
因为words
的初始值是一个空数组。在 api 调用成功之前,words
的值仍然是 []
。所以 words[0]
会 undefined
并且会出现这个错误。
要修复,您可以像这样使用 optional chaining:
<h2 className="fs-1 text-danger mb-5">{words[0]?.foreign}</h2>
...
<h2 className="fs-1 text-danger mb-5">{words[0]?.native}</h2>