frontend-interview
frontend-interview copied to clipboard
React为什么是典型FP,ReactView = render(data)怎样FP方式理解?
ReactDOM.render(
React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
),
document.getElementById('root')
);
通过 React.createElement 创造元素,通过 ReactDOM.render 进行渲染挂载。有固定的输入输出,只要给的参数一定,输出是一定的。
- FP:函数式编程(Functional Programming)
- React 遵循 $ UI = f(state) $ 即同样是数据渲染出同样的页面
- 所以 React 属于典型FP
函数式编程特性,有固定的输入输出,只要给的参数一定,输出是一定的,函数执行只以来传入的参数,且不改变外部变量
<!DOCTYPE html>
<html>
<style>
@charset "UTF-8";
</style>
<head>
<title>实现一个react render</title>
</head>
<body>
<div id="root"></div>
</body>
<script>
// 模拟react实现把一个数据模型,动态渲染到dom上
class Element {
constructor(type, props) {
this.type = type;
this.propos = props;
}
}
const react = {
creatElement: (type, props = {}, ...children) => {
return new Element(type, {
...props,
children
})
}
}
const ReactDOM = {
creatComponent: (creatComponent, container) => {
const component= creatComponent();
container.innerHTML=`<${component.type}>${component.propos.children[0]}</${component.type}>`;
}
}
//懒函数,只定义不执行,在需要的时候执行
const Title = () => react.creatElement('h1', {}, 'hello word');
//执行creatComponent,创建元素并渲染到dom上
ReactDOM.creatComponent(Title, document.getElementById('root'));
</script>
</html>
React为什么是典型的FP?ReactView = render(data) 怎样以FP的方式理解?
函数式编程的特性:
1、数据不可变(Immutable)
-
在React中,强调一个组件不能去修改传入的prop值,也是遵循Immutable的原则;
-
在Redux中,更是强调Immutable的作用,每个reducer不能够修改state,只能返回一个新的state
2、纯函数
-
在React中,组件的render函数应该是一个纯函数,只有这样组件渲染的结果才只和 state/props 有关系,遵循
这个公式;
-
在Redux,reducer 必须是一个纯函数,也是函数式编程的要求
另外 React 官网也说 React 可以使用声明式编写UI,让你的代码更加可靠,且方便调试。
以及函数式组件,hooks,都是函数式编程的体现。