reactjs - useSelector 不会从 Redux 存储返回当前值
问题描述
在这里反应初学者。
我正在使用 true 或 false 的值更新Redux
商店。result
我想稍后在另一个组件中使用该值。我用一个用 包裹的函数调度该值useEffect
,该result
值位于依赖数组中。(结果在本地状态被初始化为假。)
export const Sudoku = () => {
const dispatch = useDispatch()
const [result, setResult] = useState(false)
const puzzle = useSelector(store => store.sudoku.easySudoku)
const solution = useSelector(store => store.sudoku.easySudokuSolution)
const elapsedSeconds = useSelector(store => store.sudoku.time)
const accessToken = useSelector(store => store.user.login.accessToken)
const username = useSelector(store => store.user.login.username)
//compare the two arrays:
const isCorrect = () => {
for (let i = 0; i < solution.length; i++) {
for (let j = 0; j < solution[i].length; j++) {
if (solution[i][j] !== Number(puzzle[i][j])) {
return false
}
}
}
return true
}
const postToLeaderboard = () => {
fetch(LEADERBOARD_URL, {
method: 'POST',
body: JSON.stringify({ username: username, time: elapsedSeconds }),
headers: { 'Content-Type': 'application/json' },
})
.then((response) => {
console.log(response.json())
if (!response.ok) {
// eslint-disable-next-line
throw "Sorry, could not post to leaderboard";
}
else console.log("response was ok!")
// return response.json();
})
}
const dispatchResult = () => {
dispatch(sudoku.actions.updateResult({ result }))
}
useEffect(() => {
dispatchResult()
// eslint-disable-next-line
}, [result])
const evaluateGame = () => {
if (isCorrect()) {
if (elapsedSeconds > 30) {
postToLeaderboard()
setResult(true)
console.log("Hej, this is true!")
} else {
console.log("No time, this is true!")
setResult(true)
}
} else {
console.log("This is false!")
setResult(false)
}
}
if (accessToken) {
return (
<>
<Header />
<Timer />
<Grid />
{/* <Link to={`/result`}> */}
<Button
variant="contained"
color="primary"
type="submit"
onClick={evaluateGame}>
Check solution!
</Button>
{/* </Link> */}
</>
)
} else {
return <LoginHere text={"Want to play sudoku?"} />
}
}
当我单击一个按钮并触发一个进行一些评估的函数时,该result
值正在更改。
按钮被包裹<Link>
以引导到我接下来要进入的页面并使用result
商店中的更新值(即按钮单击触发的函数的结果)。
我注意到Redux
当我不使用时,商店会更新为正确的值<Link>
,但是,当我使用它并且最终到达所需的页面时,从商店中检索到的值不正确,尽管在控制台中可以看到, “没时间,这是真的!” 正在被打印出来,这意味着result
刚才被设置为 true 。
非常感谢您的帮助。谢谢!
解决方案
推荐阅读
- latex - 表格中的新命令
- google-sheets - 如何在 Google 表格中按司机计算平均每小时吨数?
- excel - 基于上个月的 Excel 公式
- javascript - 在 JavaScript 中使用“new”关键字创建包装的 BigInt 或 Symbol 有区别吗?
- javascript - html中的内容可编辑段落
- python - 如何创建一个简单的 python web 服务,它将在本地运行并处理并行请求
- apim - APIM 命名值通过 powershell/cli 创建/更新
- python - 检查数组的值
- openssl - 使用 prime256v1 私钥加密/解密的 openssl 命令?
- javascript - 谷歌地图(参考错误:谷歌未定义)