react 18 npm: lst 版本
{
"name": "04_learn_redux",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.3.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^8.0.5",
"react-scripts": "5.0.1",
"redux": "^4.2.1",
"redux-thunk": "^2.4.2",
"web-vitals": "^2.1.4"
}
我看文档上写的这个用 connect 高阶函数 用 mapStateToProps 去获取值传给组件 但是我打印了 props 是 {}
pages/about.jsx
import React, {PureComponent} from 'react';
import { connect } from 'react-redux'
export class About extends PureComponent {
render() {
console.log("about",this.props)
const { counter } = this.props
console.log("about",counter) //控制台显示 about undefined
return (
<div>
<h2> About Counter: {counter}</h2>
</div>
);
}
}
// 传入 组件的 state 然后返回一个隐射关系 因为不是 store 里的所有数据我们都需要
const mapStateToProps = state => ({
counter: state.counter
})
// connect 是一个高阶函数 调用方法为 connect(函数 1 ,函数 2)(组件)
export default connect(mapStateToProps)(About);
store/index.js
import {createStore} from "redux";
import reducer from "./reducer";
const store = createStore(reducer)
export default store
stote/reducer.js
import * as actionTypes from "./constants"
const initialState = {
counter: 100
}
function reducer(state = initialState, action) {
switch (action.type) {
case actionTypes.ADD_NUMBER:
return { ...state, counter: state.counter + action.num }
case actionTypes.SUB_NUMBER:
return { ...state, counter: state.counter - action.num }
case actionTypes.CHANGE_BANNERS:
return { ...state, banners: action.banners }
case actionTypes.CHANGE_RECOMMENDS:
return { ...state, recommends: action.recommends }
default:
return state
}
}
export default reducer
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux'
import store from './store'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
{/* 包裹 最顶层 传入一个 store */}
<Provider store={store}>
<App/>
</Provider>
</React.StrictMode>
);
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.