首页 > 解决方案 > React-Redux 调度设计

问题描述

概述

我们有一个带有标题(蓝色)和内容部分(绿色)的页面,如下图所示。要求是当用户在标题中选择年份时,内容页面将根据所选年份显示数据。

在此处输入图像描述

现在发生了什么 技术上

当用户在 header 中选择年份时,我们调度选定的值并mapStateToProps触发活动容器的功能,并将选定的年份传递给组件。

class Page1Content extends Component {
}

function mapStateToProps(state) {
    return { selectedYear : state.userSelectedValue };
}

export default connect(mapStateToProps, null)(Page1Content);

问题 1

数据Page1Content将如何刷新?几种方法:

  1. 在APIComponentDidUpdate的 react 生命周期中Page1Content可以调用获取数据的方法。然而,已经看到了一些意见,我们应该在 Redux 中避免使用 React 钩子和生命周期方法。
  2. mapStateToProps函数 API 中可以调用。

任何人都可以建议调用 API 的更好位置吗?

问题2

上的数据Page1Content将仅用于此页面。此数据不会被任何其他组件使用,因此不需要由任何其他组件共享。现在问题2是

  1. 如果我们决定使用ComponentDidUpdate,我们是否应该再次使用Thunk或任何其他库调度 API 调用,然后mapStatesToProps再次捕获响应?
  2. 或者我们应该进行 API 调用并在组件本身中将其作为一个 Promise 来解决。然后将在状态中设置响应,并刷新相应的模板。

标签: reactjsreduxredux-thunkreact-hooks

解决方案


ComponentDidUpdate 是一个生命周期方法而不是一个钩子。Hooks 是一种功能,它允许功能组件具有基于类的功能,例如状态。您在示例中使用了基于类的组件,因此您没有使用钩子。

https://reactjs.org/docs/hooks-intro.html

是的,Redux 不应该与钩子一起使用,因为上下文是更好的选择。

可以说,您可以提升状态并更新父组件中的本地状态,从而完全摆脱 redux。

只需将 setState 函数和状态本身传递给适当的孩子。

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
               some_prop: false
             }
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({some_prop: true})
    console.log('Click happened');
  }
  render() {
    return (
     <Header onClick={this.handleClick } />
     <Page1Component props={this.state.some_prop} />
  }
}

编辑:

问题 1

Page1Content 上的数据将如何刷新?

最好的选择是在您的渲染方法中使用三元表达式,无需检查状态是否已更新。如果状态发生变化,您的组件将自动重新渲染。

  render() {
    return (
      <div>
        {this.props.selectedYear
           ? <p> {this.props.selectedYear}</p>
           : null 
         }
      </div>       

  }
}

问题2

Page1Content 上的数据将仅供该页面使用。此数据不会被任何其他组件使用,因此不需要由任何其他组件共享。现在问题2是

如果我理解正确,您将需要使用动作创建者,redux thunk 在这里是多余的。

class Header extends Component {
  constructor(props) {
    super(props);
  }

  handleClick() {
    this.props.dispatchActionCreator({some_value})
    console.log('Click happened');
  }
  render() {
    return (
      <button onClick={(some_value) => this.handleClick(some_value)}>Click </button>
  }
}

function mapDispatchToProps(state) {
    return { 
       dispatchActioNCreator: (some_value) => dispatch(ACTIONS.action_creator(some_value) };
}

这会将您的值从您的标头保存到全局 redux 状态,然后您可以在 Page1Component 中使用 mapStateToProps 进行访问。


推荐阅读