我的 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/