We talked about in the last article that if we want to achieve cross-end reuse of components, we must reuse the logic layer.
Looking back and reviewing the development of the front-end in the past few years, we can see that due to the rise of Vue, React frameworks, etc., the front-end is more and more heavy on the View layer, which is basically based on view components, and organizes code around the latitude of user interaction. For example the following component:
const calendar = (props) => {
const [state, setState] = React.useState(props)
return(
<div onClick={()=> setState()}>
{state}
</div>
)
}
It has its own View and data processing logic (state+props). How to deal with this piece of data depends on how the user interacts with the View layer and what data is needed. This works well in most scenarios, but for our current multi-terminal business scenario, either each terminal writes its own logic independently (no reuse, the efficiency is too low), or reuses common logic (common logic It needs various judgment environments, and then uses the corresponding platform api, which is very cumbersome)
For example, there will be the following code:
// 充斥各种环境判断
const fetch = () => {
if(isRn) return Rnfetch;
if(isH5) return h5Fetch;
...
}
Therefore, we can turn our attention to the logical processing. Take the model layer as the core, and don't care which end is connected:
In this way, the ability of the model is enhanced, and the View layer is simply a function to obtain the state from the Model layer and change the state. Secondly, APIs for different platforms, such as fetch above, can be solved by injection.
// model.tsx
const wrapModel = ({fetch})=()=> {
const getUserInfo = ()=>{
fetch(url,{xxx})
}
const useActions = ()=>{
getUserInfo
}
}
// rn page.tsx
const model = wrapModel({fetch: rnFetch})
const Page = ()=> {
const { getUserInfo } = model.useActions();
return xxxx;
}
We can see that in this way, the reuse of components is achieved to the greatest extent, and the cumbersome environmental judgment can be avoided.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。