【问题标题】:Cant get redux state from component无法从组件获取 redux 状态
【发布时间】:2021-11-29 09:20:12
【问题描述】:

简单的计数器应用程序。单击按钮时状态正在按预期变化,我可以在 redux 开发工具中进行跟踪。但是我无法从计数器组件访问 count redux 状态。我到底做错了什么?

import React,{useState} from 'react'
import { connect } from 'react-redux';
import  addone from '../actions/addone';



const Counter = ({addone,count}) => {
    
    console.log(count);
    return (
        <div>
            <h1>Value:{count}</h1>
            <button type="button" onClick={()=>addone()}>Add 1</button>

        </div>
    )
}


const mapStateToProps = (state) => ({
    count:state.count
  });

export default connect(mapStateToProps, { addone })(Counter);

输出值后不显示任何内容。

【问题讨论】:

  • 乍一看,这看起来不错。 addone() 和 reducer 长什么样子?

标签: javascript node.js reactjs redux frontend


【解决方案1】:

你需要在我编辑你的代码的功能组件中使用useSelector钩子:

import React,{useState} from 'react';
import { useSelector} from 'react-redux';
import  addone from '../actions/addone';

const Counter = () => {
    const count = useSelector((state) => state.count);
    console.log(count);
    return (
        <div>
            <h1>Value:{count}</h1>
            <button type="button" onClick={()=>addone()}>Add 1</button>

        </div>
    )
}

【讨论】:

  • 他们使用的是connect函数,所以你不需要使用useSelector钩子。
猜你喜欢
  • 2021-11-23
  • 1970-01-01
  • 2021-07-09
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 2022-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多