admin管理员组

文章数量:1334693

I hope you can help.

I can't remember where I got the the snippet of code in the deleteHandler function. It deletes the relevant listdata item from the JSON array and re-renders as expected. I just don't understand what it's doing. Is it specific React syntax? Is it rudimentary stuff that I am oblivious to?

I know the state.listdata.splice(id, 1); line gets the current JSON object, but what does the arrow function do? What is being returned? I'm quite baffled by it.

Any help is much appreciated.

var AppFront = React.createClass({
  getInitialState:function(){
    return{
        listdata: [
          {"id":1,"name":"Push Repo","description":"Job No 8790","priority":"Important"},
          {"id":2,"name":"Second Note","description":"Job No 823790","priority":"Important"}
          ]
    }
  },
  deleteHandler: function(e,id){
    this.setState(state => {
      state.listdata.splice(id, 1);
      return {listdata: state.listdata};
    });
  },
    render: function(){
    var listDataDOM = this.state.listdata.map((item,index) => {return (<li key={item.id}>
        {item.name}
        <button onClick={()=>this.deleteHandler(item.id)}>delete</button>
      </li>)});
    return(
      <div>
        <h1>To-do List</h1>
        <ul>
        {listDataDOM}
        </ul>
      </div>
    );
  }
  });
  
  ReactDOM.render(<AppFront />,document.getElementById("container"));
<script src=".1.0/react.min.js"></script>
<script src=".1.0/react-dom.min.js"></script>

I hope you can help.

I can't remember where I got the the snippet of code in the deleteHandler function. It deletes the relevant listdata item from the JSON array and re-renders as expected. I just don't understand what it's doing. Is it specific React syntax? Is it rudimentary stuff that I am oblivious to?

I know the state.listdata.splice(id, 1); line gets the current JSON object, but what does the arrow function do? What is being returned? I'm quite baffled by it.

Any help is much appreciated.

var AppFront = React.createClass({
  getInitialState:function(){
    return{
        listdata: [
          {"id":1,"name":"Push Repo","description":"Job No 8790","priority":"Important"},
          {"id":2,"name":"Second Note","description":"Job No 823790","priority":"Important"}
          ]
    }
  },
  deleteHandler: function(e,id){
    this.setState(state => {
      state.listdata.splice(id, 1);
      return {listdata: state.listdata};
    });
  },
    render: function(){
    var listDataDOM = this.state.listdata.map((item,index) => {return (<li key={item.id}>
        {item.name}
        <button onClick={()=>this.deleteHandler(item.id)}>delete</button>
      </li>)});
    return(
      <div>
        <h1>To-do List</h1>
        <ul>
        {listDataDOM}
        </ul>
      </div>
    );
  }
  });
  
  ReactDOM.render(<AppFront />,document.getElementById("container"));
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>

Share Improve this question edited Aug 31, 2016 at 8:20 Kokovin Vladislav 10.4k5 gold badges40 silver badges36 bronze badges asked Jul 10, 2016 at 12:55 Moe-JoeMoe-Joe 1,0303 gold badges15 silver badges29 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

1) About setState

setState function in React looks something like that :

setState(partialState, callback)

Where partialState may be : object , function or null.

In your particular case you use function, which returns an object of state variables.

setState(function(state){ return {some:data}  })

and with arrow func (es6) , the same will look like

setState(state=> { return {some:data}  })

in yout particular case arrow func used just for short


2) About splice

In handler, you use JS func splice() to remove element from state's array;

But it is bad practice, because it mutates the state of ponent.And It will cause bugs, problems and unpredictable behavior. You shouldn't mutate your state!

To avoid that you can copy your array through slice(), because slice returns new array.

      var newArray = state.listdata.slice()
      newArray.splice(index, 1);

3) About deleteHandler and data structure

deleteHandler doesnt work properly, and works only for first position.And if your data will look like that:

 listdata: [
          {"id":52,"name":"Push Repo","description":"Job No 8790","priority":"Important"},
          {"id":11,"name":"Second Note","description":"Job No 823790","priority":"Important"}
          ]

It will not work at all

For proper result , you should change deleteHandler to this:

 deleteHandler: function(e,id){
      //find index of element
      var index = this.state.listdata.findIndex(e=>e.id==id);
      //copy array
      var newAray = this.state.listdata.slice();
      //delete element by index
      newAray.splice(index, 1);
      this.setState({listdata: newAray});

  },

and button

<button onClick={e=>this.deleteHandler(e,item.id)}>delete</button>

> JSBIN example

or you can delete by index

 deleteHandler: function(e,index){
      //copy array
      var newAray = this.state.listdata.slice();
      //delete element by index
      newAray.splice(index, 1);
      this.setState({listdata: newAray});
  },
 <button onClick={e=>this.deleteHandler(e,index)}>delete</button>

> JSBIN example

In your AppFront ponent you have a state

{
        listdata: [
          {"id":1,"name":"Push Repo","description":"Job No 8790","priority":"Important"},
          {"id":2,"name":"Second Note","description":"Job No 823790","priority":"Important"}
        ]
    }

It represents initial data in your ponent. Every time you change state, your ponent gets rerendered.

You can change state by calling ponent's setState method

In deleteHandler

deleteHandler: function(e,id){
    this.setState(state => {
      // state.listdata - array of initial values,
      state.listdata.splice(id, 1);
      return {listdata: state.listdata}; // returns a new state
    });
  }

state.listdata.splice(id, 1) // removes an element with index == id from the array. You should not confuse listdata item.id and item index. In order for your code to work correctly you need to pass index in you deleteHandler.

<button onClick={()=>this.deleteHandler(index)}>delete</button>

Another thing is that you call deleteHandler only with one argument - item index so in your definition it should be

  deleteHandler: function(index){
    this.setState(state => {
      // state.listdata - array of initial values,
      state.listdata.splice(index, 1);
      return {listdata: state.listdata}; // returns a new state
    });
  }

In your render method you iterate through this.state.listdata and return React.DOM nodes for each.

When you update ponent's state it gets rerendered and you see that item was deleted.

This code is written in es2015 so if it's new to you, it's better to start from reading something about new syntaxis.

state.listdata.splice(id, 1) deletes 1 element with the index equal to id from listdata array. For example if id equals to 0, then, after applying state.listdata.splice(id, 1), state.listdata will bee:

listdata: [          
      {"id":2,"name":"Second Note","description":"Job No 823790","priority":"Important"}
      ]

And exactly this array will be returned by this arrow functions.

Keeping in mind, that splice method receives index as first argument, but you pass id property there, most probably you should change this code:

<button onClick={()=>this.deleteHandler(item.id)}>delete</button>

To:

<button onClick={()=>this.deleteHandler(index)}>delete</button>

本文标签: javascriptReact JSHow does this function work to delete JSON dataStack Overflow