【问题标题】:Copying redux state to component state is good way to optimize react app?将 redux 状态复制到组件状态是优化 React 应用程序的好方法吗?
【发布时间】:2019-09-24 12:24:59
【问题描述】:

当我需要更改应用程序状态时,我将部分 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 选择器。 这是优化应用程序的好方法还是应该只对减速器进行所有更改?

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    我相信没有太大的不同,因为最后你想保存/编辑你的数据,所以你需要在最后发送一个request

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

    如果你没有/改变一些局部变量你应该使用状态,否则你应该使用你的redux store

    希望对你有帮助。

    【讨论】:

    • 我的意思是用户名更改将调度许多动作,用户保存将调度一个动作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2016-07-25
    • 2017-08-17
    • 2017-10-27
    相关资源
    最近更新 更多