首页 > 解决方案 > 为什么这个地图函数在反应中接收对象而不是字符串。我需要使用 item.item 来呈现一个字符串

问题描述

我正在尝试在有效的数组中添加这个简单的待办事项字符串,但是当我在地图中使用它并渲染它时,我需要使用 item.item 让它工作,如果我只使用 item 我收到一个错误的 objecs作为 React Child 无效...顺便说一句,这是与 redux 一起使用的。我该如何解决这个问题?

这是列表显示

const todos=useSelector(state=>state)
 <table>
        <tbody>
        <tr>
            <th>note</th>
            <th>remove</th>
            <th></th>
        </tr>
        {
            todos.map(item=>(
                <List item={item}/>
            ))
        }
        </tbody>
    </table>

这是列表项:

    <tr>
    <td>{item.item}</td>
    <td>x</td>
    <td></td>
    </tr>

这是我添加它的方法

const AddList=()=>{
const [newItem,setNewItem]=useState("")
const dispatch=useDispatch()
const handleAdder=(e)=>{
    e.preventDefault()
    dispatch(addItem(newItem))
}

return(
  <div>
    <form onSubmit={(e)=>handleAdder(e)}>
    <input value={newItem} onChange={(e)=>setNewItem(e.target.value)}></input>
    <button type="submit">add</button>
    </form>
  </div>
)
}

这是减速机

const todoReducer=(state=[],action)=>{

    switch(action.type){
        case('ADD_ITEM'):
        return [...state,action.newItem]
        default:{
            return state
        }
        
    }
}
export default todoReducer

标签: javascriptreactjsreact-redux

解决方案


因为 todos 是对象数组,如果您不想使用 item.item,只需像这样使用对象破坏:

 <table>
        <tbody>
        <tr>
            <th>note</th>
            <th>remove</th>
            <th></th>
        </tr>
        {
            todos.map(item=>(
                <List {...item} key={item.id}/>
            ))
        }
        </tbody>
    </table> 

这会将所有对象键作为子组件的道具传递。

不要忘记key在每个组件上添加 for map 方法。


推荐阅读