什么会导致state.mapfoo => <> {foo} </>中显示的状态不一致?

问题描述

第一个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,state.length)]
        default: throw new Error();
    }
}
function Fees() {
    const [state,[])
    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>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...