How I can assign some values of redux store to my component local state?
I should use redux actions to get data from API in my componentDidMount() method. Am I right? after getting data by redux I want to set my component's state using the data from redux store.I got an error this.props.article is undefined., but redux devtools shows that article object exists.
Where I supposed to call this.setState() method ??? I tried to call it in componentWillRecieveProps() or componentDidUpdate() , but unsuccessfuly. Please any help.Thank you in advance.
import React, { Component, Fragment } from 'react';
import { Typography,Spin } from 'antd';
import {connect} from 'react-redux';
import {getArticleDetails} from '../store/actions/articles';
class ArticleEdit extends Component {
articleID = this.props.match.params.articleID;
state={
str:'initial'
}
onChange = (str) => {
console.log('Content change:', str);
this.setState({ str1:str });
};
componentDidMount(){
this.props.getArticleDetails(this.articleID);// GET data from api
this.setState({str:this.props.article.title});// returns undefined
}
render() {
return (
<Fragment>
{this.props.article===undefined?(<Spin/>):
(
<div>
<div style={{marginRight:'500px'}}>
<Paragraph editable={{ onChange: this.onChange}}>
{this.state.str}
</Paragraph>
</div>
</div>
)}
</Fragment>
)
}
}
const mapStateToProps = state =>({
article: state.articleReducer.articles[0],
})
export default connect(mapStateToProps,{getArticleDetails})(ArticleEdit);
答案 0 :(得分:4)
如Henrik所说,您想使用this.props
而不是this.state
。您已经使用mapStateToProps检索了一篇文章,这很好。如果要将文章标题传递给组件,则可以在render()方法中添加一些代码,如下所示:
render() {
const { article } = this.props
const { title } = article
return (
...
<Paragraph editable={{ onChange: this.onChange}}>
{title}
</Paragraph>
...