首页 > 解决方案 > 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 。

非常感谢您的帮助。谢谢!

标签: reactjsreact-redux

解决方案


推荐阅读