reactjs - 如何在 componentDidMount 中使用通过 Redux 获取的值
问题描述
我曾尝试在 React + Redux 中开发应用程序。我的问题是使用 Redux 获取的值不能用于componentDidMount()
. Redux 的值只在 中使用render()
,但是你有什么想法在渲染之前使用值。
我的代码:
class User extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { id } = this.props.match.params;
this.props.fetchUser(id);
const { user } = this.props;
console.log("user", user);
// This is my issue, I can't get user here!
}
render() {
const { user } = this.props;
console.log("user", user);
return (
<p>{user.name}</p>
)
}
function mapStateToProps({ users }) {
return { user: users };
}
export default connect(mapStateToProps, { fetchUser })(User);
动作代码:
export function fetchUser() {
return dispatch => {
firebase.auth().onAuthStateChanged(user => {
roomsRef
.doc(user.uid)
.get()
.then(doc => {
dispatch({ type: FETCH_USER, payload: doc.data() });
});
});
};
}
减速器
import { FETCH_USER } from "../actions";
const initialState = {};
export default (state = initialState, action) => {
switch (action.type) {
case FETCH_USER:
return action.payload;
default:
return state;
}
};
店铺
const rootReducer = combineReducers({
users: UsersReducer,
});
const store = createStore(rootReducer, applyMiddleware(reduxThunk));
export default store;
解决方案
这样做并做出反应将寻找用户
state={
user:null
}
componentDidMount = () => {
this.props.fetchUser(id);
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.user !== prevState.user) {
return { user: nextProps.user };
}
else return null;
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.user !== this.props.user) {
//Perform some operation here
this.setState({ user: this.props.user });
// do what you wanna do with user here
console.log(this.state.user) //would return user obj here
}
}
与 Redux 类似
const mapStateToProps = state => {
return {
user: state.UsersReducer.user
}
}
const mapDispatchToProps = dispatch => {
return {
fetchUser: (id) => dispatch(actions.yourreduxfunc(id)),
}
}
推荐阅读
- r - 如何在 R 中运行双交叉分类的 3 级分层线性模型?HLM 中的 DIF
- vue.js - 用户离开组件后如何重置状态
- autodesk-forge - `versions:batch-get` 不获取“标题”自定义属性
- python - 计算条件熵
- sql-update - 是否有通过用另一列(在相关表中)中的数据(不同类型)替换一列来更新表的 SQL 函数?
- flask - 如何使 Flask Heroku 应用程序成为渐进式 Web 应用程序 (pwa)
- javascript - Adobe Illustrator 脚本可删除没有笔划的路径
- java - 如何为 JComboBox 中的每个值创建加法分配?
- c# - 提高 Blazor .NET 5.0 中许多子组件(Quill JS 富文本编辑器)的性能?
- javascript - 让最基本的 ajax 在 Windows 7 上的 xampp 上工作以检查互联网连接