reactjs - React-Redux 调度设计
问题描述
概述
我们有一个带有标题(蓝色)和内容部分(绿色)的页面,如下图所示。要求是当用户在标题中选择年份时,内容页面将根据所选年份显示数据。
现在发生了什么 技术上
当用户在 header 中选择年份时,我们调度选定的值并mapStateToProps
触发活动容器的功能,并将选定的年份传递给组件。
class Page1Content extends Component {
}
function mapStateToProps(state) {
return { selectedYear : state.userSelectedValue };
}
export default connect(mapStateToProps, null)(Page1Content);
问题 1
数据Page1Content
将如何刷新?几种方法:
- 在API
ComponentDidUpdate
的 react 生命周期中Page1Content
可以调用获取数据的方法。然而,已经看到了一些意见,我们应该在 Redux 中避免使用 React 钩子和生命周期方法。 - 在
mapStateToProps
函数 API 中可以调用。
任何人都可以建议调用 API 的更好位置吗?
问题2
上的数据Page1Content
将仅用于此页面。此数据不会被任何其他组件使用,因此不需要由任何其他组件共享。现在问题2是
- 如果我们决定使用
ComponentDidUpdate
,我们是否应该再次使用Thunk
或任何其他库调度 API 调用,然后mapStatesToProps
再次捕获响应? - 或者我们应该进行 API 调用并在组件本身中将其作为一个 Promise 来解决。然后将在状态中设置响应,并刷新相应的模板。
解决方案
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 进行访问。
推荐阅读
- python - 无法使用 cv2 播放整个视频
- python - 如何根据输出错误重新运行特定的 pytest 测试
- sdk - 应该使用哪个 Azure ServiceBus SDK?
- xml - 使用 bash 脚本从 XML 文件中提取特定关键字
- c++ - C++ 语句“if”被忽略
- python - 如何创建一条知道起点、终点和距离的路线
- python - 获取数字列表并检查其中是否存在中间峰-Python
- c# - 在没有 ConfigurationManager 的情况下从 App.config 读取 ConnectionString
- c++ - 是否可以从 Visual Studio 2019 的终端运行构建任务?
- python - 如果您使用 repl.it,如何调用本地文件/在线文件?