【发布时间】:2019-08-10 04:16:07
【问题描述】:
如何将一些 redux store 的值分配给我的组件本地状态?
我应该在 componentDidMount() 方法中使用 redux 操作从 API 获取数据。我对吗?通过 redux 获取数据后,我想使用 redux store 中的数据设置组件的状态。我收到错误 this.props.article is undefined.,但 redux devtools 显示文章对象存在。 p>
我应该在哪里调用 this.setState() 方法???我试图在 componentWillRecieveProps() 或 componentDidUpdate() 中调用它,但没有成功。 请任何帮助。在此先感谢您。
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);
【问题讨论】:
-
从技术上讲,如果您在使用 Redux 时使用了 action creators/thunk 来获取数据,那么您应该不将来自 API 的数据设置为本地状态。您应该将其用作
props。 -
是的,我明白你的意思。但是我有一个 onChange 方法,我想用它来编辑我文章的标题。所以这就是为什么我认为我应该使用状态。我如何处理没有状态的 onChange 方法???
标签: reactjs redux react-redux