【问题标题】:.map is not a function when using useDispatch or useState in onClick在 onClick 中使用 useDispatch 或 useState 时,.map 不是函数
【发布时间】:2021-03-05 09:36:24
【问题描述】:

我有一系列来自 redux 的映射数据,将组件显示为阶段 1 和阶段 2。(将来我计划有更多)我想要的是根据组件的 id 调度一个动作.这是我的做法:

const stageList = stages.map ((stage)=> 
    <Stage key={stage.id} onClick={()=>dispatch(selectStage(stage.id))}
        stagename={stage.name} exp={stage.exp} id={stage.id}/>
)

实际的组件是这样构建的

const Stage = ({onClick, stagename, exp, id}) => {
    return (
        <div onClick={onClick} className={styles.item}>
            <img style={{height:"15em"}} alt="Map of the Stage" src={map}></img>
            <div className={styles.inner}>
                <h4>Stage {id}: {stagename}</h4>
                <p>LVL {exp}</p>
            </div>
        </div>
    )
}

但每当我尝试时,我都会得到:

stages.map 不是函数

它也不是 redux 状态,因为 console.log(state.id) 工作正常并输出正确的阶段 id。 我试过的方法是使用 useState 和 useEffect 来使用 useState 获取 stage.id 值并在它更新时调度状态。

const [stageSelected, setStageSelected] = useState(0);

useEffect(() => {
    dispatch(selectStage(stageSelected));
    console.log(stageSelected);
}, [stageSelected])

const info = useSelector(state => state.info);
const dispatch = useDispatch();

const stages = info.stages

const stageList = stages.map ((stage)=> 
    <Stage key={stage.id} onClick={()=> setStageSelected(stage.id)}
        stagename={stage.name} exp={stage.exp} id={stage.id}/>
)

但也无济于事。

阶段的价值是

stages: [
    {
        name: "Health and Safety",
        tagname:"healthAndSafety",
        id:0,
        exp:3,
        steps: [
            {
                name: "Correct Uniform",
                tagname:"correctUniform",
            },
            {
                name: "Coffee Machine",
                tagname:"coffeeMachine",
            },
            {
                name: "Food Safety",
                tagname:"foodSafety",
            },
        ]
    },
    {
        name: "Customer Service",
        tagname:"customerService",
        id:1,
        exp:5,
        steps: [
            {
                name: "Correct Uniform",
                tagname:"correctUniform",
            },
            {
                name: "Coffee Machine",
                tagname:"coffeeMachine",
            },
            {
                name: "Food Safety",
                tagname:"foodSafety",
            },
        ]
    }
]

我试图找到一个类似的答案(使用 setState 和 componentDidChange),但不幸的是我在问题中找不到相同的组合

【问题讨论】:

  • stages的值是多少?
  • 啊,当然。我刚刚发布了阶段的价值
  • 我的假设是,有时你会得到数组(上面提到过)。当它失败时,你必须找到它。
  • 啊哈!我检查了 stage 失败时的值,这实际上是 redux reducer 错误地更改状态的问题。谢谢!我应该发布动作创建器和减速器,但我不认为这是相关的抱歉

标签: reactjs redux onclick react-hooks use-state


【解决方案1】:

这实际上是减速器的问题,它错误地改变了状态。应该张贴减速机对不起。无论如何谢谢@UKS

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2020-03-06
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多