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);