redux进阶2

react-redux
帮助我们在react中方便使用redux

在src目录下只有一个index.js的js文件

首先安装它
创建TodoList.js
src下创建文件夹store
store下创建index.js
store下创建reducer.js

reducer.js
const defaultState ={
inputValue :' ',
list: []}
export default (state=defaultState,action) =>{
 if(action.type === 'change_input_value') {
 const newState =JSON.parse(JSON.stringify(state));
 newState.inputValue =action.value;
 return newState;}
  if(action.type === 'add_item') {
 const newState =JSON.parse(JSON.stringify(state));
 newState.list.push(newState.inputValue);
 newState.inputValue=' ';
 return newState;}
return state;
}
store/index.js
import { createStore }from 'redux';
import reducer from './reducer';
const store = createStore();
export default store;
TodoList.js

import React,{Component } from 'react';
//import store from './store';
import { connect } from  'react-redux';

class TodoList extends Component {
//constructor(props_{
//super(props);
//this.state =store.getState();
}
render(){
//const {inputValue,changeInputValue,handleClick} =this.props;
//有这一行时 this.props.inputValue就可以改成inputValue了

return (
<div>
	<div>
		<input value={this.props.inputValue}
		onChange={this.props.ChangeInputValue}/>
		//{this.state.inputValue}/>
		<button 
		onClick {this.handleClick.bind(this)}>提交</button>
	</div>
	<ul>
		{
		this.props.list.map((item,index)=>{
			return <li onClick={this.props.handleDelete} key={index}>{item}</li>
		})
		}
	</ul>
 <div>
	 )
 }

 
 }
 const mapStateToProps = (state) => {
 //把store里state里的inputValue映射到组件里的inputValue
 return {
 	inputValue:state.inputValue,
 	list:state.list
 }
 const mapDispatchToProps =(dispatch) =>{
 return {
 ChangeInputValue(e){
 const action ={
 type:'change_input_value',
 value:e.target.value
 }
	 dispatch(action);
 }
 handleClick(){
 const action = {
 	type:'add_item'
 }
 dispatch(action);
 },
 handleDelete(){
 	.....//同理
 }
 }
 }
 }
 export default connect(mapStateToProps,mapDispatchToProps)(TodoList);
 //使TodoList组件和store进行链接
 //数据映射在mapStateToProps 对数据修改是mapDispatchToProps
 
 //export default TodoList;
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from'./TodoList';
import { Provider }from 'react-redux'
import store from './store';

const App =(
	<Provider store={store}> 
	//提供器提供了store 则里面所有组件都能获取到store里的内容
		<TodoList />
	</Provider>//也是一个组件 react-redux的核心API
ReactDOM.render(App,document.getElementById('root'));
//ReactDOM.render(<TodoList />,document.getElementById('root'));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值