【问题标题】:Set state of react component by using redux store使用 redux store 设置 React 组件的状态
【发布时间】: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


【解决方案1】:

正如 Henrik 所说,您想使用 this.props 而不是 this.state。您已经使用 mapStateToProps 检索了一篇文章,这很好。如果你想将文章标题传递给你的组件,你可以在你的 render() 方法中添加一些代码,如下所示:

render() {
    const { article } = this.props
    const { title } = article
    return (
            ...
                      <Paragraph editable={{ onChange: this.onChange}}>                          
                           {title}
                      </Paragraph>
            ...

【讨论】:

  • 好的,谢谢你的回答,但是我如何使用我的 onChange 方法???
  • @PrunusArmeniaca 如果你使用 Redux 来管理你的状态,你需要设置一个 action 和 reducer 来改变 redux 存储。您的标题不应仅在 React 组件的状态下更改。这能回答你的问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-17
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
相关资源
最近更新 更多