🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ //src>routes>indexpages import React from 'react'; import { connect } from 'dva'; import styles from './IndexPage.css'; function IndexPage(props) { const additem = () => { // const value = document.querySelector('input').value; // console.log(props) //把跟新后的数据放在list中传递过去进行跟新 const actionchadd = { type: 'example/handleAdd', // list: props.list } props.dispatch(actionchadd); } //回车触发的事件,并调用输入框中的值 const keyupadditem=(e)=>{ if (e.which !== 13) return // console.log('你按了回车键...') additem() } //获取输入框中的值 const handleChange = (e) => { const actionchange = { type: 'example/handleChange', value: e.target.value } props.dispatch(actionchange); // console.log(e.target.value) } + const deleteitem = (e) => { // console.log(e) const actiondeleteitem = { type: "example/deleteitem", index: e, list: props.list } props.dispatch(actiondeleteitem) + } return ( <div className={styles.normal}> <input onChange={ async e => { // e.persist() await handleChange(e) }} value={props.value} onKeyPress={keyupadditem}/> <button onClick={additem}>添加</button> <ul> {props.list.map((item, index) => { + return <li key={index}><div><span>{item}</span><button onClick={deleteitem.bind(this, index)}>删除</button></div></li> })} </ul> </div> ); } // IndexPage.propTypes = { // }; //用于连接模板文件与models文件 export default connect(({ example }) => { return { //接收models的state中的数据 list: example.list, value: example.value } })(IndexPage); ~~~ ~~~ // src>models>example.js export default { namespace: 'example', state: { list: [], value: '' }, subscriptions: { setup({ dispatch, history }) { }, }, effects: { *fetch({ payload }, { call, put }) { // eslint-disable-line yield put({ type: 'save' }); }, }, reducers: { save(state, action) { return { ...state, ...action.payload }; }, //接收传递过来的type和value并将其展开和state一起返回,换回出来的数据可供全局使用,在handleadd中可使用 handleChange(state, value) { // console.log(value.value) return { ...state, value: value.value }; }, //将handlechange中的 handleAdd(state, args) { //经过判断将value的值添加到list中去(value是handlechange中返回的value,此处的list是页面上要渲染的数据) // console.log(args) if (!state.list.includes(state.value)&&!state.value=='') { state.list.push(state.value); } // console.log(state.list) //处理函数里面一定要有return函数,且return后面的语句不执行 return { list: state.list, value:'' } }, deleteitem(state, args) { // console.log(args.index) //不能直接修改state中的值,要复制一份进行修改state中的数据 var newlist = args.list.slice(0); // console.log(newlist) newlist.splice(args.index, 1); // const list =[1,2,3] // console.log(newlist) return { list:newlist } } }, }; ~~~