最近我一直在尝试将我的 React 组件编写为“纯函数”,我注意到有时我想要一些感觉很像状态
的东西。我正在考虑将我的 state
作为第二个参数传递给我的组件。我可以通过将我的组件作为具有两个参数 props
和 state
的普通函数来调用来实现此目的。
例如:
// abstracted to it's own module
const useState = (Component, state = {}) => {
return class extends React.Component {
state = createState(this, state); // will traverse and update the state
render() {
const { props, state } = this;
return Component(props, state); // <-- call the Component directly
}
};
};
const Component = (props, { index, increase }) => (
<div onClick={increase} {...props}>
Click me to increase: {index}
</div>
);
const componentState = {
index: 0,
increase: (event, state) => ({ ...state, index: state.index + 1 })
};
const StatefullComponent = useState(Component, componentState);
<StatefullComponent style={{ color: "purple" }} />;
我有一个 CodeSandbox 示例:
我的问题是:
- 这种模式会损害性能吗?
- 我不再用状态值扩展 props,这可能是一件好事
- 我弄乱了组件的默认渲染方式,这可能是一件坏事
- 此模式会破坏诸如
shouldComponentUpdate
之类的内容吗? (我有一种沉闷的感觉,这是在对旧的context
api 进行建模) - 我应该有多担心 future 的 React 更新会破坏此代码?
- 是否有一种更“响应式(Reactive)”的方式在纯函数中使用 State,而不需要借助 Redux 等库?
- 我是否正在尝试解决一些不应该解决的问题?
注意:在本例中我使用的是state
,但它也可以是主题
、授权规则或您可能认为的其他内容想要传递到您的组件中。
最佳答案
乍一看,当我检查你的代码时,我有一个问题:
"Why do you make it so complicated? When you can simply make it with a class declaration".
但后来当我有splitted your code时我发现这样做确实值得。
问题 1:并没有真正的区别,这只是 HOC 进行组合的方式。
I'm no longer extending the props with state values, this might be a good thing
为什么/什么时候这可能是一件好事?
I am messing with the way components are rendered by default, this might be a bad thing
我没有看到默认情况下你会破坏或弄乱渲染,我认为 HOC模式提倡相同的理念,即将状态与 Prop 分开的区别。
问题 2:如果开发人员决定使用无状态组件,那么他/她应该意识到所有“生命周期方法”或引用 ref
将不可用。
您的模式使无状态组件成为“有状态”,但在无状态声明中 - 太棒了😋。
就像在 JSX
中一样,您在 JS 中编写一个“HTML”,并在其中编写带有另一个“HTML”的 JS 代码:
<ul>
{list.map(text => <li>text</li>)} // I know there should be used key
</ul>
先生Baudin
模式(全状态就像无状态):
import React from 'react'
import {useState} from './lib'
const state = {
index: 0,
increase: (event, state) => ({index: state.index + 1})
}
const Component = (props, state) => (
<div onClick={state.increase} {...props}>
Click me to increase: {state.index}
</div>
)
export default useState(Component, state)
问题 3:这取决于 future 版本中的重大更改。
问题 4: 嗯...我不认为提供的模式(实现的库)可以被视为应用程序状态管理,但它可以在任何状态管理(如 Redux 或 Mobx)中使用,因为它处理内部组件状态。
问题 5:不,我不这么认为。您的解决方案使代码更少、更干净。函数式组件适用于非常简单或代表性的组件,现在可以通过状态进行扩展。
关于reactjs - 在 React 中将更多参数传递给纯渲染函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49272407/