簡體   English   中英

什么會導致 state.map(foo =&gt; &lt;&gt;{foo}</> ) 在反應中顯示?

[英]What can cause inconsistency in state.map(foo => <>{foo}</>) display in react?

第一個 jsx/tsx 代碼正確顯示 state.map 而第二個什么都不顯示。 為什么? 這兩段代碼以同樣的方式做同樣的事情,但是,盡管進行了許多調整,一個列表仍然正確顯示,而另一個 state.map 從未呈現任何內容

import React from 'react';
import './App.css'
const { useReducer } = require("react");
function reducer(state, action) {
  switch (action.type) {
    case 'add': return [...state, action.item]
    case 'rm': return [...state.slice(0, action.index), ...state.slice(action.index + 1, state.length)]
    default: throw new Error();
  }
}
function Todo() {
  const [state, dispatch] = useReducer(reducer, [])
  return (
    <div className="App">
      <h1>TO DO</h1>
      <p>
        <button onClick={() => dispatch({ type: 'add', item: prompt('?') })}>+</button>
        <button onClick={() => dispatch({ type: 'rm', index: prompt('?') - 1 })}>-</button>
        <button onClick={() => dispatch({ type: 'rm', index: prompt('?') - 1 })}></button>
        <ol>{
          state.map((item) => (
            <>{item}</>
          ))}</ol>

      </p>

    </div>
  )
}
export default Todo

////////////////////////////////////////////////// ///////////////

import React from 'react';

const { useReducer } = require("react");
function reducer(state, action) {
    switch (action.type) {
        case 'add': return [...state, action.item]
        case 'rm': return [...state.slice(0, action.index), ...state.slice(action.index + 1, state.length)]
        default: throw new Error();
    }
}
function Fees() {
    const [state, dispatch] = useReducer(reducer, [])
    return (
        <body>
            <h1>Fees {state}</h1>
            <p>
                <button onClick={() => dispatch({ type: 'add', item: prompt('Expense?') + prompt('Amount?') })}>+</button>
                <button onClick={() => dispatch({ type: 'rm', index: prompt<number>('line number?') - 1 })}>-</button>
                <table>
                    <tr>
                        <th>
                            Expense
                            </th>
                        <th>
                            Amount
                            </th>
                        {state.map((item) => {
                            <td> {item}</td>
                        })}
                    </tr>
                    <tr><td>Total</td></tr>
                </table>
            </p>
        </body>
    )
}
export default Fees

我看到函數prompt是聲明:

declare function prompt(message?: string, _default?: string): string | null;

您可以稍后刪除返回值的類型分配,僅和驗證 int :

 <button onClick={() => dispatch({ type: 'rm', index: prompt('line number?') - 1 })}>-</button>

在 React 中,您需要從 map 返回一個組件以使其呈現。 第一個示例默認返回,因為您使用了括號,而第二個示例沒有。 括號需要顯式的 return 語句。

暫無
暫無

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

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