What's Redux !? Redux 是一个用来集中管理state的一个library,
用了Redux我们可以直接取得或修改相同的state,不用再一层一层Component往下传了!
执行以下指令安装redux
npm install redux
在App.js的地方镶上React Redux 的Provider ,且透过redux的createStore来建立store
import { createStore } from "redux";
import reducer from './reducers'
const store = createStore(reducer)
class App extends React.Component {
render() {
return (
<Provider store={store}>
<Component />
</Provider>
);
}
}
上面的程序码我们会看到在建立store的时候需要传入reducer (也就是放置action type 并回传新store的地方),所以我们要建立reducer并传入
let initialState;
initialState = {
aa:""
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case "action1":
return {
...state,
aa:"123"
};
break;
case "action2":
return {
...state,
aa:"333"
};
break;
default:
return { ...state };
break;
}
};
上述程序码,我们在switch里使用到action.type,通常我们会建立一个新的js档案来放置action
export const action1 = ()=>{
return {type:'action1'}
};
export const action2 = ()=>{
return {type:'action2'}
};
在其他Component连结store的方式 (连结state和dispatch)
连结state
const mapStateToProps = (state) => {
return { aa: state.aa };
};
连结dispatch
const mapDispatchToProps = (dispatch) => {
return {
action1:()=>{dispatch(action1())},
action2:()=>{dispatch(action2())}
};
};
以上是Redux的原理及使用方法的补充,
下一篇要来介绍跟Redux作用很像的React Query ,
小菜鸟个人是觉得React Query相对Redux好用满多的 (⊙ꇴ⊙)
<<: [Angular] Day27. Validating form input
>>: Day13-React 表单验证篇-使用第三方函式库 Formik 进行表单的验证
昨天我们提到了如何透过元件区分出独立的资料流,但问题来了,如果两个元件的资料需要互通有无呢? 这时候...
一个图形具有两个集合的基本组成:G(V,E) V:表示顶点的集合 V(G1)={1,2,3,4} E...
接下来我要用一个小应用来介绍基本的 CRUD 实作:复仇者英雄列表。它的功能如下: 新增英雄到列表中...
1.use static or Router express.static =>Web 服务器...
更新: Bug解掉了,在第28天 今天真的没办法思考.. 还没抓到昨天的错误是为什麽,然後接下来的学...