簡體   English   中英

單擊按鈕后重定向並在不同的路線上呈現選項卡

[英]Redirect after click on button and render a tab on a different route

單擊一組難度按鈕后,我想在“/game”路由中渲染一個 Tabel 組件。 因此,應用程序必須根據在 DifficultyButtons.js 中設置的難度 state 從路由“/”傳遞到“/game”來呈現正確的表格。 我在 App.js 中管理 Route 組件,如下所示:`

      <Route path='/' render={() => <DifficultyButtons/>} />
      <Route path='/game' render={() => <Table/>} />

`

在文件 DifficultyButtons.js 中,重定向從單擊設置 state“難度”的按鈕開始,該按鈕將在文件 Table.js 中使用,我的目的是根據設置的難度級別按比例呈現表格。 這是 Table.js:

`

const location = useLocation();
const rows = N*location.state;
const columns = M*location.state;


return (

    <Table responsive>
        <tbody>
        {Array.from({length: rows}).map((_, row_index) => (
            <tr key={row_index}>
                {Array.from({length: columns}).map((_, column_index) => (
                    <td key={column_index}>
                        try
                    </td>
                ))}
            </tr>
        ))}
        </tbody>
    </Table>
    </div>
)

` 這是渲染比例表的正確方法嗎? 我想了解為什么重定向到“/game”不起作用。 DifficultButtons.js 中的重定向代碼:

{selected ? (
        <Redirect to={{
            pathname: '/game',
            state: {level:difficulty}
        }}

這是呈現比例表的正確方法嗎?

這是一個相當主觀的問題,但我認為您映射“二維數組”的方式沒有任何明顯的問題。

我想了解為什么重定向到"/game"不起作用。

重定向和傳遞 state 時,您正在傳遞state.level上的難度級別

<Redirect
  to={{
    pathname: '/game',
    state: { level: difficulty }
  }}
/>

但僅在目標路由的組件中引用location.state

const location = useLocation();
const rows = N * location.state;
const columns = M * location.state;

由於location.state是 object 計算的結果很可能rowscolumns都是NaN s。

Dereference the passed level value from the route state, provide safe default value for level if it's not passed in route state, and also a default value for state if a user somehow navigates directly to "/game" where the route state will be simply undefined .

const location = useLocation();
const { state: { level = 0 } = {} } = location;

const rows = N * level;
const columns = M * level;

您詢問有關響應按鈕單擊的重定向,在這種情況下,您不能只從回調中調用/返回Redirect組件並期望它影響正在呈現的任何內容。 為此,您需要發出命令式重定向。 使用history object 以使用適當的 state 進行重定向。

const history = useHistory();

...

// in some button's onClick handler
history.replace({
  pathname: '/game',
  state: { level: difficulty }
});

您可以使用“react-router-dom”中的“鏈接”來代替“重定向”。

<Link to="/game?level=difficulty" />

您可以在https://v5.reactrouter.com/web/api/Link訪問 v5 的官方文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM