将redux状态复制到组件状态是优化React应用的好方法吗?

时间:2019-09-24 12:24:59

标签: javascript reactjs redux

当我需要更改应用程序状态时,我将部分redux状态复制到组件状态,并像这样使用本地状态

export class User extends React.Component {
  state = {
    user: this.props.user,
  };

  render() {
    return (
      <div>
        <input
          value={this.state.user.name}
          onChange={this.changeUserName}
        />
        <button onClick={this.saveUser}>Save</button>
      </div>
    );
  }

  userNameChange = ({target}) => {
    this.setState((prevState) => ({
      user: {
        ...prevState.user,
        name: target.value,
      },
    }));
  }

  saveUser = () => {
    const {
      userActions,
    } = this.props;

    const {
      user,
    } = this.state;

    userActions.save(user);
  }
}

const mapStateToUserProps = (state) => ({
  user: state.user,
});

const mapDispatchToUserProps = (dispatch) => ({
  userActions: bindActionCreators(UserActions, dispatch),
})

export const UserContainer = connect(mapStateToUserProps, mapDispatchToUserProps)(User);

这将防止调用redux选择器。 是优化应用程序的好方法还是应该仅对减速器进行所有更改?

1 个答案:

答案 0 :(得分:0)

我相信没有什么不同,因为最后您要保存/编辑数据,因此需要在末尾发送request

创建具有更少请求的应用程序更为重要,如果您有大数据,则应尝试在server-side中尽可能多地过滤数据。

如果没有/更改某些局部变量,则应使用状态,否则应使用redux store

希望对您有帮助。