javascript - ReactJs mapStateToProps

标签 javascript reactjs redux react-redux

我的 React 应用程序遇到一些问题。 我正在尝试对用户进行身份验证并从后端获取一些数据,而 mapStateToProps 没什么问题。 这就是我成功获得唯一用户的方法:

 const mapStateToProps = ({auth}) => {
  const {authUser} = auth;
  return {authUser}
};

这就是我从 api 获取数据的方式,也成功了

const mapStateToProps = (state) => {
  return {
    serversList: state.servers.servers,
  }
}

现在我需要以某种方式组合 mapStateToProps,我尝试了不同的方法,例如:

 const mapStateToProps = ( state, auth ) => {
        const {authUser} = auth;
        return {
            authUser,
            serversList: state.servers.servers,
        }
    };

在这种情况下,它不会验证用户身份。 如何将它们结合起来?

这是我的完整代码,没有一些导入:

import { requestServers  } from '../../../appRedux/actions';

const mapStateToProps = ( state, auth ) => {
    const {authUser} = auth;
    return {
        authUser,
        serversList: state.servers.servers,
    }
};


const mapDispatchToProps = (dispatch) => {
return {
  onRequestServers: () => dispatch(requestServers())
}
}


class Dashboard extends Component {


    componentDidMount() {
        this.props.onRequestServers();
      }


    render() {
        const {authUser} = this.props;
        const { serversList } = this.props;


        return (
            <Row>
        <Col xl={12} lg={24} md={12} sm={24} xs={24}>
        <UserInfo userName={authUser ? authUser.name : "Guest"}/>
        </Col>
        <Col xl={12} lg={24} md={12} sm={24} xs={24}>
          <BillingProfile balance={authUser ? authUser.stanje : "0"}/>
        </Col>
            <Col span={24}>
            <Servers />
            </Col >
            </Row>

        );
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)

最佳答案

应该是

const mapStateToProps = (state) => {
    const {authUser} = state.auth;
    return {
        authUser,
        serversList: state.servers.servers,
    }
};

const mapStateToProps = ({servers, auth}) => {
    const {authUser} = auth;
    return {
        authUser,
        serversList: servers.servers,
    }
};

mapStateToProps 的第二个参数是 ownProps 而不是 auth。 您需要的是从状态中提取的auth

关于javascript - ReactJs mapStateToProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60445158/

相关文章:

javascript - 跟踪 redux-form 上禁用字段的最佳方法

reactjs - 如何返回 Redux reducer 的状态

javascript - 使用combineReducers()组合两个reducer时出现错误

javascript - Typescript/Javascript 自定义属性装饰器

javascript - 根据ID显示具体数据

Javascript 正则表达式 Lookbehind 替代方案

javascript - 如何一次只在一个数组元素上 setState?

php - 为什么这个 JQuery/AJAX 调用不起作用?

reactjs - React Hooks 必须在每个组件渲染中以完全相同的顺序调用

reactjs - React 路由器导航栏示例