【问题标题】:how to add an item to a list in React.js?如何在 React.js 中将项目添加到列表中?
【发布时间】:2017-01-01 13:48:49
【问题描述】:

我正在尝试将一个项目添加到 React.js 中的列表中。这是我的代码: https://plnkr.co/edit/JEG6o4JCBIQWAt2A4S3r?p=preview

当用户单击添加按钮时,我想将输入字段的文本值添加到列表中。在我的演示中,我有add button,点击后我想将该项目添加到列表中。 你能告诉我哪里做错了吗?

Code:

const { createStore, bindActionCreators, applyMiddleware,combineReducers } = Redux;
const { Provider, connect } = ReactRedux;
const thunk = window.ReduxThunk.default;


const first_redux =function(state ='' ,action){
  switch (action.type){
    case 'ADD_ITEM':
     return action.payload
    default :
    return state

  }
}

const actions ={
 addItem :function(item){
  return {
    type :"ADD_ITEM",
    payload :item
  } 
 }  

}
var combindReducer = combineReducers({
  item:first_redux
})

const store = createStore(combindReducer);

class First extends React.Component {
  constructor (props){
    super(props);
    this.state = {
      names :[],
      username :''
    }
   this.changeEv =this.changeEv.bind(this);
   this.addName =this.addName.bind(this);
  }
  changeEv(e){
    this.setState({
      username : e.target.value
    })
  }
  addName(){
   // this.state.names.push(this.state.username);
    console.log(this.state);
    this.props.add(this.state.username)
  }

  render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    var listItems = this.state.names.map(function(d, idx){
      return (<li key={idx}>{d.name}</li>)
    })
    return (
      <div>
      <input type="text" onChange ={this.changeEv}/>
      <button onClick={this.addName}>add</button>
      {listItems}
      </div>
    );
  }
} 

function mapStateToProps(state){
  console.log('=================');
  console.log(state);
  return {
       names: state.item,

  };
    console.log(this.state);

}

function mapDispatchToProps(dispatch){
  return {
    add:bindActionCreators(actions.addItem,dispatch)
  }
}
const Appcontainer =connect(mapStateToProps,mapDispatchToProps)(First)

ReactDOM.render(
  <Provider store ={store}>
    <Appcontainer/>
    </Provider>
  ,document.getElementById('root'));

【问题讨论】:

    标签: reactjs redux react-router react-redux


    【解决方案1】:

    我对您的代码进行了一些更改,在这种情况下,当您使用 redux 时,store 位于组件之外,并且 mapDispatchToProps 正在将全局状态与组件的 props 进行映射。

    // 代码在这里

    const { createStore, bindActionCreators, applyMiddleware,combineReducers } = Redux;
    const { Provider, connect } = ReactRedux;
    const thunk = window.ReduxThunk.default;
    
    const initialState = []
    
    const first_redux =function(state = initialState ,action){
      switch (action.type){
        case 'ADD_ITEM':
         let newState = action.payload;
         return [...state,newState];
        default :
        return state
    
      }
    }
    
    const actions ={
     addItem :function(item){
      return {
        type :"ADD_ITEM",
        payload :item
      } 
     }  
    
    }
    var combindReducer = combineReducers({
      item:first_redux
    })
    
    const store = createStore(combindReducer);
    
    class First extends React.Component {
      constructor (props){
        super(props);
        this.state = {
          username :''
        }
       this.changeEv =this.changeEv.bind(this);
       this.addName =this.addName.bind(this);
      }
      changeEv(e){
        this.setState({
          username : e.target.value
        })
      }
      addName(){
       // this.state.names.push(this.state.username);
        console.log(this.state);
        this.props.add(this.state.username)
      }
    
      render() {
        const data =[{"name":"test1"},{"name":"test2"}];
        var listItems = this.props.names.map(function(d, idx){
          return (<li key={idx}>{d}</li>)
        })
        return (
          <div>
          <input type="text" onChange ={this.changeEv}/>
          <button onClick={this.addName}>add</button>
          {listItems}
          </div>
        );
      }
    } 
    
    function mapStateToProps(state){
      console.log('=================');
      console.log(state);
      return {
           names: state.item,
    
      };
        console.log(this.state);
    
    }
    
    function mapDispatchToProps(dispatch){
      return {
        add:bindActionCreators(actions.addItem,dispatch)
      }
    }
    const Appcontainer =connect(mapStateToProps,mapDispatchToProps)(First)
    
    ReactDOM.render(
      <Provider store ={store}>
        <Appcontainer/>
        </Provider>
      ,document.getElementById('root'));
    

    https://plnkr.co/edit/e6oJXempwk0e5GciOSSB?p=previewp

    【讨论】:

      【解决方案2】:

      您在 reducer 中返回的基本上是应用程序的状态,但现在您只是返回有效负载,因此在这种情况下,您的状态只是一个项目。但是,您想要的是让您的状态成为项目列表,因此您的状态应该创建一个数组,而不仅仅是返回有效负载。请注意,reducer 中的状态应该是不可变的,因此我们不能简单地将新的有效负载推送到最后一个状态。

      这是一个如何实现的示例:

      const first_redux = function(state = [] ,action){
        switch (action.type){
          case 'ADD_ITEM':
            return [
              ...state,
              action.payload
            ];
          default :
            return state
        }
      }
      
      var combindReducer = combineReducers({
        items: first_redux
      })
      
      function mapStateToProps(state){
        console.log('=================');
        console.log(state);
        return {
          names: state.items,
        };
      }
      

      【讨论】:

        猜你喜欢
        • 2019-11-26
        • 1970-01-01
        • 2017-07-14
        • 2018-04-04
        • 2016-06-08
        • 1970-01-01
        • 2014-08-23
        相关资源
        最近更新 更多