1、引入react-redux,在模板渲染口,使用Provider提供store,只要在Provider中使用的组件都可以调用到store中的state状态
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import store from './store'
import { Provider } from 'react-redux'
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
2、在要使用store的组件中使用connect连接组件,通过mapStateToProps映射state到组件的props上,和mapDispatchToProps
将action映射到props上,然后正常调用
import React, { Component } from 'react';
import TodoListUi from './components/TodoListUi'
import TodoListItem from './components/TodoListItem'
import { connect } from 'react-redux'
import {
addInputValue,
addListItem,
delListItem,
} from "./store/actionCreators";
class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<TodoListUi
text={this.props.inputValue}
changeInputValue={this.props.changeInputValue}
addListInputValue={this.props.addListInputValue}
></TodoListUi>
{this.props.list.map((item, index) => {
return (
<TodoListItem
key={index}
context={item}
order={index}
delListItem={this.props.delListItem.bind(this, index)}
></TodoListItem>
);
})}
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
// 将state映射到props上
return {
inputValue: state.inputValue,
list: state.list
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
// 将action映射到props上
return {
changeInputValue: (data) => {
// 改变input的内容
dispatch(addInputValue(data))
},
addListInputValue: () => {
// 改变input的内容
dispatch(addListItem())
},
delListItem: (data) => {
// 删除子项
dispatch(delListItem(data))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);