【发布时间】:2019-02-09 15:47:58
【问题描述】:
大家好,请您帮我解决这个问题:
我正在使用 react + firebase + redux
类中的最后几行如下所示(编辑帖子页面):
const mapStateToProps = (state, ownProps) => {
const id = ownProps.match.params.id;
const posts = state.firestore.data.posts;
const post = posts ? posts[id] : null;
return {
post: post,
auth: state.firebase.auth
};
};
const mapDispatshToProps = (dispatch, ownProps) => {
return {
editPost: (id, post) => dispatch(editPost(id, post, ownProps.history))
};
};
export default compose(
connect(
mapStateToProps,
mapDispatshToProps
),
firestoreConnect([{ collection: "posts" }])
)(CreatePost);
之后我使用 componentDidMount 来获取这样的帖子:
componentDidMount() {
const post = this.props.post;
console.log(post);
this.setState({
title: post ? post.title : "",
content: post ? post.content : ""
});
}
我也使用过 componentWillReceiveProps :
componentWillReceiveProps(nextProps) {
const { post } = nextProps;
console.log(post);
this.setState({
title: post.title,
content: post.content
});
}
我的 ipnut 是这样的:
<input type="text" id="title" value={this.state.title} onChange={this.handleChange} />
控制台总是显示null
我没有成功更新状态(查看更新的唯一方法是刷新页面)
你能帮帮我吗,
谢谢
【问题讨论】:
-
你不应该使用componentWillReceiveProps,它从版本16开始被弃用,并且将在版本17中被删除。改用
static getDerivedStateFromProps。 -
嘿Piotr,我试过
static getDerivedStateFromProps,但这个函数是static,它不能访问this.state。我该怎么办? -
getDerivedStateFromProps有两个参数:props, state。如您所见,第一个是当前道具,第二个是当前状态。你应该在这个方法中返回新的状态,所以它看起来像这样:static getDerivedStateFromProps(props, state) { let newState = {...state}; newState.foo = props.foo; return newState; }
标签: reactjs firebase react-redux