#17 React-redux 实现用户列表的显示、增加、删除


  • 0

    /**
     * 环境中已经注入了 React-redux,你可以直接使用 connect,或者 ReactRedux.connect
     */
    
    const usersReducer = (state, action) => {
      if (!state) state = []
      switch (action.type) {
        case 'ADD_USER':
          state = [...state, action.user]
          break
        case 'DELETE_USER':
          state = state.filter((u, i) => action.index !== i)
          break
        case 'UPDATE_USER':
          state = state.map((u, i) => (action.index === i) ? {...u, ...action.user} : u)
          break
      }
      
      return state
    }
    
    class User extends Component {
      render () {
        const { user } = this.props
        return (
          <div>
            <div>Name: {user.username}</div>
            <div>Age: {user.age}</div>
            <div>Gender: {user.gender}</div>
            <button onClick={this.props.onDel}>删除</button>
          </div>
        )
      }
    }
    
    class UsersList extends Component {
      state = {
        username: '',
        age: undefined,
        gender: undefined
      }
      onInputChange = (evt) => {
        let { target: { name, value} }  = evt
        if (name === 'age') value = Number(value)
        this.setState(() => ({
          [name]: value
        }))
      }
      
      handleClick = () => {
        this.props.onAdd(this.state)
      }
      render () {
        return (
          <div>
            {/* 输入用户信息,点击“新增”按钮可以增加用户 */}
            <div className='add-user'>
              <div>Username: <input type='text' 
                name="username" 
                value={this.state.username}
                onChange={this.onInputChange}
                />
              </div>
              <div>Age: <input type='number' 
                name="age"
                value={this.state.age}
                onChange={this.onInputChange}
                />
              </div>
              <div>Gender:
                <label>Male: <input type='radio' name='gender' value='male' 
                  onChange={this.onInputChange}/></label>
                <label>Female: <input type='radio' name='gender' value='female' 
                  onChange={this.onInputChange}/></label>
              </div>
              <button onClick={this.handleClick}>增加</button>
            </div>
            {/* 显示用户列表 */}
            <div className='users-list'>
              {
                this.props.list.map((u, i) => <User key={i} user={u} onDel={() => {this.props.onDel(i)}}/>)
              } 
            </div>
          </div>
        )
      }
    }
    
    
    UsersList = connect(state => ({
      list: state
    }),
    dispatch => ({
      onAdd: (user) => dispatch({ type: 'ADD_USER', user}),
      onDel: (index) => dispatch({ type: 'DELETE_USER', index}),
    }))(UsersList)
    
    
    

  • 0

    在本地一直都是成功的,但是在平台上就显示新增后返回新数组... 好吧我没审好题,要直接使用那个 usersReducer 。。。要有 'UPDATE_USER' 。。。。磨了这么久。。。。。。

    
    const usersReducer = (state = [], action) => {
      switch (action.type) {
        case 'ADD_USER': {
          return [...state, action.user];
        }
        case 'DELETE_USER': {
          let newState = [...state]
          newState.splice(action.index, 1)
          return newState;
        }
        case 'UPDATE_USER':
          let upState = [...state];
          upState[action.index] = {...upState[action.index], ...action.user};
          return [...upState];
        default:
          return state
      }
      return state
    }
    
    // const usersReducer = (state=[], action) => {
    //   switch (action.type) {
    //     case 'ADD_USER': 
    //       return [...state, action.user];
    //     case 'DELETE_USER':
    //       let deState = [...state];
    //       deState.splice(action.index, 1);
    //       return [...deState];
    //     case 'UPDATE_USER':
    //       let upState = [...state];
    //       upState[action.index] = {...upState[action.index], ...action.user};
    //       return [...upState];
    //     default:
    //       return state;
          
    //   }
    // }
    
    class User extends Component {  
      render () {
        const { user } = this.props
        return (
          <div>
            <div>Name: {user.username}</div>
            <div>Age: {user.age}</div>
            <div>Gender: {user.gender}</div>
            <button onClick={() => this.props.onButtonClick(this.props.index)}>删除</button>
          </div>
        )
      }
    }
    
    class UsersList extends Component {
      constructor () {
        super()
        this.state = {
          username: '',
          age: 0,
          gender: ''
        }
      }
      
      handleInputChange (prop, e) {
        var value = e.target.value
        if (prop === 'age') value = parseInt(value)
        this.setState({
          [prop]: value
        })
      }
      
      render () {
        return (
          <div>
            {/* 输入用户信息,点击“新增”按钮可以增加用户 */}
            <div className='add-user'>
              <div>Username: 
                <input type='text' 
                  value={this.state.username}
                  onChange={this.handleInputChange.bind(this, 'username')} />
              </div>
              <div>Age: 
                <input type='number' 
                  value={this.state.value} 
                  onChange={this.handleInputChange.bind(this, 'age')} />
              </div>
              <div>Gender:
                <label>Male: <input type='radio' name='gender' value='male' 
                  onClick={this.handleInputChange.bind(this, 'gender')} /></label>
                <label>Female: <input type='radio' name='gender' value='female'
                  onClick={this.handleInputChange.bind(this, 'gender')} /></label>
              </div>
              <button onClick={() => this.props.addUser(this.state)}>增加</button>
            </div>
            {/* 显示用户列表 */}
            <div className='users-list'>
              {this.props.userList.map(
                (user, index) => <User user={user} key={index} index={index} onButtonClick={this.props.deleteUser.bind(this)}/>)
              }
            </div>
          </div>
        )
      }
    }
    
    const mapStateToProps = (state) => {
      console.log(state)
      return {
        userList: state
      }
    }
    
    const mapDispatchToProps = (dispatch) => {
      return {
        addUser: (user) => {
          dispatch({
            type: 'ADD_USER',
            user: user
          })
        },
        deleteUser: (index) => {
          dispatch({
            type: 'DELETE_USER',
            index
          })
        }
      }
    }
    
    UsersList = connect(mapStateToProps, mapDispatchToProps)(UsersList)
    

  • 0

    /**
     * 环境中已经注入了 React-redux,你可以直接使用 connect,或者 ReactRedux.connect
     */
    
    const ADD_USER = "ADD_USER"
    const DELETE_USER = "DELETE_USER"
    const UPDATE_USER = "UPDATE_USER"
    
    const usersReducer = (state = [], action) => {
      switch(action.type) {
        case 'ADD_USER':
          return [...state, action.user];
        case 'DELETE_USER':
          return state.filter((item, index) => index !== action.index);
        case 'UPDATE_USER':
          return [...state.map((item, index) => {
            if (index === action.index) {
              return { ...item, ...action.user }
            } else {
              return item
            }
          })]
        default:
          return state;
      }
    }
    
    class User extends Component {
      handleDelete = index => {
        this.props.deleteUser(index)
      }
      render () {
        const { user, index } = this.props
        return (
          <div>
            <div>Name: {user.username}</div>
            <div>Age: {user.age}</div>
            <div>Gender: {user.gender}</div>
            <button onClick={() => this.handleDelete(index)}>删除</button>
          </div>
        )
      }
    }
    
    class UsersList extends Component {
      state = {
        username: '',
        age: '',
        gender: '',
      }
      handleChangeName = e => {
        const username = e.target.value
        this.setState({ username })
      }
      handleChangeAge = e => {
        const age = Number(e.target.value)
        this.setState({ age })
      }
      handleChangeGender = e => {
        const gender = e.target.value
        this.setState({ gender })
      }
      handleAdd = () => {
        this.props.addUser(this.state)
      }
      render () {
        const { username, age, gender } = this.state
        const { addUser, deleteUser, users } = this.props
        return (
          <div>
            {/* 输入用户信息,点击“新增”按钮可以增加用户 */}
            <div className='add-user'>
              <div>Username: <input type='text' value={username} onChange={this.handleChangeName} /></div>
              <div>Age: <input type='number' value={age} onChange={this.handleChangeAge} /></div>
              <div>Gender:
                <label>Male: <input type='radio' name='gender' value='male' onChange={this.handleChangeGender} /></label>
                <label>Female: <input type='radio' name='gender' value='female' onChange={this.handleChangeGender} /></label>
              </div>
              <button onClick={this.handleAdd}>增加</button>
            </div>
            {/* 显示用户列表 */}
            <div className='users-list'>
              {
                users.map((item, index) => {
                  return <User user={item} deleteUser={deleteUser} index={index} key={index} />
                })
              }
            </div>
          </div>
        )
      }
    }
    
    const mapStateToProps = state => ({ users: state })
    const mapDispatchToProps = (dispatch, state) => {
      return {
        addUser: user => {
          dispatch({
            type: 'ADD_USER',
            user: user,
          })
        },
        deleteUser: index => {
          dispatch({
            type: 'DELETE_USER',
            index: index,  
          })
        }
      }
    }
    
    UsersList = connect(
      mapStateToProps,
      mapDispatchToProps
    )(UsersList)
    
    

  • 0

    @陈小俊#17 React-redux 实现用户列表的显示、增加、删除 中说:

    class User extends Component {
      render () {
        const { user, onDeleteUser, index} = this.props
        return (
          <div>
            <div>Name: {user.userName}</div>
            <div>Age: {user.age}</div>
            <div>Gender: {user.gender}</div>
            <button onClick={()=> {onDeleteUser(user, index)}}>删除</button>
          </div>
        )
      }
    }
    
    class UsersList extends Component {
      constructor() {
        super();
        this.state = {
          index: 0,
          userName: '',
          age: '',
          gender: ''
        }
      }
      
      render () {
        const { userName, age, gender } = this.state
        const { onAddUser, onDeleteUser, users } = this.props
    
        return (
          <div>
            {/* 输入用户信息,点击“新增”按钮可以增加用户 */}
            <div className='add-user'>
              <div>Username: <input type='text' value={userName} onChange={e=>{this.setState({userName: e.target.value})}} /></div>
              <div>Age: <input type='number' value={age} onChange={e=>{this.setState({age: e.target.value})}} /></div>
              <div>Gender:
                <label>Male: <input type='radio' name='gender' value='male' onChange={e=>{this.setState({gender: e.target.value})}} /></label>
                <label>Female: <input type='radio' name='gender' value='female' onChange={e=>{this.setState({gender: e.target.value})}} /></label>
              </div>
              <button onClick={()=>{this.setState({index: this.state.index+1});onAddUser(this.state)}}>增加</button>
            </div>
            {/* 显示用户列表 */}
            <div className='users-list'>
              {users.map((user, index)=>
                <User user={user} onDeleteUser={onDeleteUser.bind(this)} index={index} key={index}/>
              )}
            </div>
          </div>
        )
      }
    }
    
    
    /**
     * 环境中已经注入了 React-redux,你可以直接使用 connect,或者 ReactRedux.connect
     */
    const mapStateToProps = (state) => {
      return {
        users: state   
      }
    }
    
    const mapDispatchToProps = (dispatch) => {
      return {
        addUser: (user) => {
          dispatch({
            type: 'ADD_USER',
            user
          })
        },
        deleteUser: (user, index) => {
          console.log(index)
          dispatch({
            type: 'DELETE_USER',
            index: index,
            user
          })
        }
      }
    }
    
    class UsersContainer extends Component {
    
      render () {
        return (
          <UsersList
            users={this.props.users}
            onAddUser={this.props.addUser.bind(this)}
            onDeleteUser={this.props.deleteUser.bind(this)}
          />
        )
      }
    }
    
    const usersReducer = connect(
      mapStateToProps,
      mapDispatchToProps
    )(UsersContainer)

  • 0

    我的为什么一直提示state应该初始化为一个空数组谁能帮我看下

     * 环境中已经注入了 React-redux,你可以直接使用 connect,或者 ReactRedux.connect
     */
    
    const usersReducer = (state, {type, user, index}) => {
      if(!state){
        return {
          users: []
        }
      }
      const users = [...state.users]
      switch(type) {
        case 'ADD_USER':
          return [...users, user]
        case 'DELETE_USER':
          users.splice(index, 1)
          return users
        case 'UPDATE_USER':
          users.splice(index, 1, {...users[index], ...user})
          return users
        default:
        return state
      }
    }
    
    class User extends Component {
      render () {
        const { user } = this.props
        return (
          <div>
            <div>Name: {user.username}</div>
            <div>Age: {user.age}</div>
            <div>Gender: {user.gender}</div>
            <button onClick={() => this.props.onDeleteUser(this.props.index)}>删除</button>
          </div>
        )
      }
    }
    
    class UsersList extends Component {
      constructor() {
        super()
        this.state = {
          username: '',
          age: '',
          gender: ''
        }
      }
      render () {
        return (
          <div>
            {/* 输入用户信息,点击“新增”按钮可以增加用户 */}
            <div className='add-user'>
              <div>Username: <input onChange={({target: {value: username}}) => this.setState({username})} type='text' /></div>
              <div>Age: <input onChange={({target: {value: age}}) => this.setState({age})}type='number' /></div>
              <div>Gender:
                <label>Male: <input onChange={({target: {value: gender}}) => this.setState({gender})} type='radio' name='gender' value='male' /></label>
                <label>Female: <input type='radio' name='gender' value='female' /></label>
              </div>
              <button onClick={() => this.props.onAddUser(this.state)}>增加</button>
            </div>
            {/* 显示用户列表 */}
            <div className='users-list'>{this.props.users.map((user, i) => <User key={i} index={i} user={user}/>)}</div>
          </div>
        )
      }
    }
    
    const mapStateToProps = ({users}) => ({ users })
    const mapDispatchToProps = dispatch => ({
      onAddUser(user) {
        dispatch({type: 'ADD_USER', user})
      },
      onDeleteUser(index) {
        dispatch({type: 'DELETE_USER', index})
      }
    })
    
    UsersList = ReactRedux.connect(mapStateToProps, mapDispatchToProps)(UsersList)
    

  • 0

    有没有大佬能帮忙看一下,好像并没有执行dispatch内的方法

    /**
     * 环境中已经注入了 React-redux,你可以直接使用 connect,或者 ReactRedux.connect
     */
     
    const usersReducer = (state, action) => {
      if(!state){
        return []
      }
      switch(action.type){
        case 'ADD_USER':
          return [...state, action.user]
        case 'DEL_USER':
          return [...state, state.splice(action.index, 1)]
        default:
          return state
      }
    }
    
    class User extends Component {
      handleDel(){
        if(this.props.onDel){
          this.props.onDel(this.props.index)
        }
      }
      render () {
        const { user } = this.props
        return (
          <div>
            <div>Name: {user.username}</div>
            <div>Age: {user.age}</div>
            <div>Gender: {user.gender}</div>
            <button onClick={this.handleDel.bind(this)}>删除</button>
          </div>
        )
      }
    }
    
    class UsersList extends Component {
      constructor(){
        super()
        this.state = {
          username: '',
          age: '',
          gender: ''
        }
      }
      handleInput(e){
        const target = e.target
        this.setState({
          [target.name]: target.value
        })
      }
      handleSubmit(){
        if (this.props.onSubmit){
          this.props.onSubmit(this.state.username, this.state.age, this.state.gender)
        }
      }
      render () {
        return (
          <div>
            {/* 输入用户信息,点击“新增”按钮可以增加用户 */}
            <div className='add-user'>
              <div>Username: <input type='text' name='username' value='this.state.username' onChange={this.handleInput.bind(this)} /></div>
              <div>Age: <input type='number' name='age' value='this.state.age' onChange={this.handleInput.bind(this)} /></div>
              <div>Gender:
                <label>Male: <input type='radio' name='gender' value='male' onChange={this.handleInput.bind(this)} /></label>
                <label>Female: <input type='radio' name='gender' value='female' onChange={this.handleInput.bind(this)} /></label>
              </div>
              <button onClick={this.handleSubmit.bind(this)}>增加</button>
            </div>
            {/* 显示用户列表 */}
            <div className='users-list'>
              {this.props.users.map((user, index)=>{
                return <User user={user} key={index} index={index} />
              })}
            </div>
          </div>
        )
      }
    }
    const mapStateToProps = (state) => {
      return{
        state
      }
    }
    const mapDispatchToProps = (dispatch) => {
      return {
        onSubmit({username, age, gender}){
          dispatch({ type: 'ADD_USER', user: {username, age, gender} })
        },
        onDel(index){
          dispatch({ type: 'DEL_USER', index: index })
        }
      }
    }
    
    UsersList = connect(mapStateToProps, mapDispatchToProps)(UsersList)
    User = connect(null, mapDispatchToProps)(User)
    
    

  • 0

    @我上来就是一Jo reducer里面 if(!state)的情况下应该初始化为空数组[],而不是一个含有users属性的对象


  • 0

    const usersReducer = (state=[],action)=>{
      switch(action.type){
        case 'ADD_USER':
          return [...state,action.user]
          break;
        case 'DELETE_USER':
          return [...state.slice(0,action.index),...state.slice(action.index+1)]
          break;
        case 'UPDATE_USER':
          return [...state.map((item,i)=>{
            if(i === action.index){
              return {...item,...action.user}
            } else {
              return item
            }
          })]
          break;
        default:
        return state
        break;
      }
    }
    
    const store = createStore(usersReducer)
    
    class User extends Component {
      
      handleDelete(index){
        if(this.props.onDelete){
          this.props.onDelete(index)
        }
      }
      render () {
        const { user,index } = this.props
        return (
          <div>
            <div>Name: {user.username}</div>
            <div>Age: {user.age}</div>
            <div>Gender: {user.gender}</div>
            <button onClick={this.handleDelete.bind(this,index)}>删除</button>
          </div>
        )
      }
    }
    
    
    class UsersList extends Component {
      
      state={
        username: '',
        age: '',
        gender: '',
      }
      
      onInputChange = (e) => {
        switch(e.target.type){
          case 'text':
            this.setState({
              username: e.target.value
            })
            break;
          case 'number':
            this.setState({
              age: parseInt(e.target.value)
            })
          break;
          case 'radio':
            this.setState({
              gender: e.target.value
            })
          break;
          
        }
      }
      
      handleAdd = () => {
        if(this.props.onAdd){
          let {username, age, gender} = this.state
          this.props.onAdd({username, age, gender})
        }
      }
    
      render () {
        return (
          <div>
            {/* 输入用户信息,点击“新增”按钮可以增加用户 */}
            <div className='add-user'>
              <div>Username: <input type='text' onChange={this.onInputChange}/></div>
              <div>Age: <input type='number' onChange={this.onInputChange}/></div>
              <div onChange={this.onInputChange}>Gender:
                <label>Male: <input type='radio' name='gender' value='male' /></label>
                <label>Female: <input type='radio' name='gender' value='female' /></label>
              </div>
              <button onClick={(e)=>this.handleAdd()}>增加</button>
            </div>
            {/* 显示用户列表 */}
            <div className='users-list'>{
              this.props.users.map((user,index)=>{
                return <User {...this.props} user={user} index={index} />
              })
            }</div>
          </div>
        )
      }
    }
    
    function mapStateToProps(state){
      return {
        users: state,
      }
    }
    
    function mapDispatchToProps(dispatch){
      return {
        onAdd: (user)=>{
          dispatch({type:'ADD_USER',user})
        },
        onDelete: (index)=>{
          dispatch({type:'DELETE_USER',index})
        }
      }
    }
    
    UsersList = connect(mapStateToProps,mapDispatchToProps)(UsersList)
    

  • 0

    /**

    • 环境中已经注入了 React-redux,你可以直接使用 connect,或者 ReactRedux.connect
      */

    const userReducer = (state, action) => {
    switch (action.type) {
    case "ADD_USER":
    return {
    users: [...state.users, action.user]
    }
    case "DEL_USER":
    let users = [...state.users];
    users.splice(action.index, 1);
    return {
    users: users
    }
    default:
    return {
    users: []
    };
    }
    };

    const mapStateToProps = state => {
    return {
    users: state.users
    };
    };

    const mapDispatchToProps = dispatch => {
    return {
    addUser: user => {
    console.log("user", user);
    dispatch({
    type: "ADD_USER",
    user: user
    });
    },
    delUser: index => {
    dispatch({
    type: "DEL_USER",
    index: index
    });
    }
    };
    };

    class User extends React.Component {
    render() {
    let { user, index } = this.props;
    return (
    <div>
    <div>序号: {index}</div>
    <div>Name: {user.username}</div>
    <div>Age: {user.age}</div>
    <div>Gender: {user.gender}</div>
    <button onClick={() => {
    this.props.delUser(this.props.index)
    }}>删除</button>
    </div>
    );
    }
    }

    User = connect(
    null,
    mapDispatchToProps
    )(User);

    class UsersList extends React.Component {
    constructor() {
    super();
    this.state = {
    username: "",
    age: 0,
    gender: ""
    };
    }

    handleChange = event => {
    const { name, type, value } = event.target;
    this.setState({
    [name]: type === "number" ? +value : value
    });
    };

    handleAddUser = () => {
    this.props.addUser({
    ...this.state
    });
    }
    render() {
    return (
    <div>
    {/* 输入用户信息,点击“新增”按钮可以增加用户 /}
    <div className="add-user">
    <div>
    Username:
    <input
    type="text"
    value={this.state.username}
    name="username"
    onChange={this.handleChange}
    />
    </div>
    <div>
    Age:
    <input
    type="number"
    value={this.state.age}
    name="age"
    onChange={this.handleChange}
    />
    </div>
    <div>
    Gender:
    <label>
    Male:
    <input
    type="radio"
    name="gender"
    value="male"
    onChange={this.handleChange}
    />
    </label>
    <label>
    Female:
    <input
    type="radio"
    name="gender"
    value="female"
    onChange={this.handleChange}
    />
    </label>
    </div>
    <button onClick={this.handleAddUser}>增加</button>
    </div>
    {/
    显示用户列表 /}
    {/
    {this.props.users} /}
    {/
    <div>{[{a:1}]}</div> */}
    <div className="users-list">
    {this.props.users.map((x, index) =>
    <User user={x} index={index} key={index}/>
    )}
    </div>
    </div>
    );
    }
    }

    UsersList = connect(
    mapStateToProps,
    mapDispatchToProps
    )(UsersList);

    一直提示不是你的错,那是啥错 --


  • 0

    @bpqpqp#17 React-redux 实现用户列表的显示、增加、删除 中说:

    那些提示“修改用户以后,应该返回新的数组”的要在usersReducer加上UPDATE_USER,哪怕这题跟修改用户没关系。


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待