【发布时间】:2021-01-05 15:54:48
【问题描述】:
所以我试图通过仅提供用户 ID 从我的 redux 商店获取用户。
我的代码与 bEtTy Barnes 的代码几乎一模一样:
React Redux action object is undefined
我正在尝试将 TopicCard 组件中的用户名粘贴到 topicBy,但我只有 user_id。这就是为什么我想调用 this.handleUserByID(topics.topic_by) 但它不起作用。我还添加了一些 console.logs 来显示代码的行为方式。
第一次修复后:
我现在收到此错误:
react-dom.development.js:21 警告:在渲染不同的组件 KeyboardPage 时无法更新组件 ConnectFunction。要在 KeyboardPage 中找到错误的 setState() 调用,请按照堆栈跟踪中的说明进行操作
在 KeyboardPage 中(由 ConnectFunction 创建)
在 ConnectFunction 中(由 Context.Consumer 创建)
在 Route 中(由 PrivateRoute 创建)
在 PrivateRoute(由 App 创建)
在 Switch(由 App 创建)
在Router中(由App创建)
在 div 中(由 App 创建)
在 div 中(由 App 创建)
在 div 中(由 App 创建)
在 App 中(由 ConnectFunction 创建)
在 ConnectFunction 中
在提供者中
编辑:修复 this.props.getUser @handleUserByID 但它仍然不起作用 编辑主题作者
import React, {useEffect} from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import {topicActions, userActions} from '../../../actions';
import NavBar from '../../NavBar/NavBar';
import TopicCard from "../../ContentCard/TopicCard/TopicCard";
class KeyboardPage extends React.Component {
componentDidMount() {
this.props.getTopics(2);
}
handleUserByID(user_id){
return this.props.getUser(user_id);
}
render() {
const { topics } = this.props;
const { user, users} = this.props;
//console.log(this.props.getUser(1)) *Works but gets called multiple times and returns the correct user object
console.log(this.handleUserByID(1)); * Doesnt work;
return (
<div className="container">
<NavBar loggedinAs={user.user_name}/>
<h1>Gruppe 1 - Webforum</h1>
<h3>Topics :</h3>
{topics.loading && <em>Loading topics...</em>}
{topics.error && <span className="text-danger">ERROR: {topics.error}</span>}
{topics.items && users.items &&
<ul type='none' >
{topics.items.map((topic, index) =>
<li key={topic.topic_id}>
<p/>
<a href={"/" + topic.topic_id} style={{ textDecoration: 'none' }}>
<TopicCard topicSubject={topic.topic_subject} topicDate={topic.topic_date} topicBy={this.handleUserByID(topic.topic_by).user_name}/>
</a>
</li>
)}
</ul>
}
</div>
);
}
}
function mapState(state) {
const {topics } = state;
const { users, authentication } = state;
const { user, } = authentication;
return { user, users, topics};
}
const actionCreators = {
getTopics: topicActions.getAllbyID,
getUser: userActions.getById
}
const connectedKeyboardPage = connect(mapState, actionCreators)(KeyboardPage);
export { connectedKeyboardPage as KeyboardPage };
【问题讨论】:
-
可能将
handleUserByID()中的this.getUser()更改为this.props.getUser()? -
你是对的 - 但遗憾的是它并不能解决问题
-
那么
handleUserByID()函数返回什么? -
当我使用 console.log(this.handleUserByID(1) 我得到这个响应: ƒ (e) { return _this.props.getUser(user_id); }
-
好的,请看下面我的回答。
标签: reactjs redux react-redux