简体   繁体   English

如何使用redux和redux-thunk从服务器将获取的数据保存到组件状态?

[英]How to save fetched data from server to component state using redux and redux-thunk?

In my react app I have component named profile, and I am fetching data from server and showing it inside that component. 在我的react应用程序中,我有一个名为profile的组件,我正在从服务器中获取数据并将其显示在该组件中。 I am using redux and redux-thunk along with axios. 我正在与axios一起使用redux和redux-thunk。 With help of mapDispatchToProps function, i am calling redux action for fetching that data when component is mounted and saving it to redux state. 借助mapDispatchToProps函数,我正在调用redux操作,以在安装组件时获取该数据并将其保存为redux状态。 After that, using mapStateToProps function i am showing that data on the screen via props. 之后,我使用mapStateToProps函数通过道具在屏幕上显示该数据。 That works fine. 很好 Now I want to have possibility to edit, for example, first name of that user. 现在,我希望可以编辑例如该用户的名字。 To accomplish that i need to save that data to component state when data is fetched from server, and then when text field is changed, component state also needs to be changed. 为了实现这一点,我需要在从服务器获取数据时将数据保存到组件状态,然后在更改文本字段时,也需要更改组件状态。 Don't know how to save data to component sate, immediately after it is fetched. 提取数据后不知道如何立即将数据保存到组件状态。

Simplified code: 简化代码:

const mapStateToProps = (state) => {
    return {
        user: state.user
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        getUserData: () => dispatch(userActions.getUserData())
    }
}    

class Profile extends Component {
    state:{
         user: {}
    }

    componentDidMount (){
        this.props.getUserData()
        // when data is saved to redux state i need to save it to component state
    }

    editTextField = () => {
      this.setState({
        [e.target.id]: e.target.value
       })
    };

    render(){

        const { user } = this.props;

        return(
            <TextField id="firstName"
                   value={user.firstName}
                   onChange={this.editTextField}
            />
        )

    }
}

You can use componentDidUpdate for that or give a callback function to your action. 您可以为此使用componentDidUpdate或为操作提供回调函数。 I will show both. 我将同时展示两者。

First lets see componentDidUpdate , 首先让我们看看componentDidUpdate

Here you can compare your previous data and your present data, and if there is some change, you can set your state, for example if you data is an array. 在这里您可以比较以前的数据和现在的数据,并且如果有更改,可以设置状态,例如,如果数据是数组。

state = { data: [] }

then inside your componentDidUpdate 然后在您的componentDidUpdate内部

componentDidUpdate(prevProps, prevState) {
   if(prevProps.data.length !== this.props.data.length) {
    // update your state, in your case you just need userData, so you 
    // can compare something like name or something else, but still 
    // for better equality check, you can use lodash, it will also check for objects, 
    this.setState({ data: this.props.data});
  }
}

_.isEqual(a, b); // returns false if different

This was one solution, another solution is to pass a call back funtion to your action, 这是一个解决方案,另一个解决方案是将回调函数传递给您的操作,

lets say you call this.props.getData() 假设您调用this.props.getData()

you can do something like this 你可以做这样的事情

this.props.getData((data) => {
 this.setState({ data });
})

here you pass your data from redux action to your state. 在这里,您将数据从redux动作传递到状态。

your redux action would be something like this. 您的redux动作将是这样的。

export const getData = (done) => async dispatch => {
  const data = await getSomeData(); // or api call

  // when you dispatch your action, also call your done 
  done(data);
}

If you are using React 16.0+, you can use the static method getDerivedStateFromProps . 如果您使用的是React 16.0+,则可以使用静态方法getDerivedStateFromProps You can read about it react docs . 您可以阅读有关react docs的内容

Using your example: 使用您的示例:

class Profile extends Component {
  // other methods here ...

  static getDerivedStateFromProps(props) {
    return {
      user: props.user
    }
  }

  // other methods here...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM