Manipulating element state values

React Developer Tools lets you inspect the current state of elements that you select. You can also monitor state changes as they happen, as was demonstrated in the preceding section where you had set up an interval timer that changed the state of your element over time. The state of an element can also be manipulated in limited ways.

For this next example, let's modify the MyList component to remove the interval timer and simply populate the state when it's constructed:

import React, { Component } from 'react'; 
import MyItem from './MyItem';
class MyList extends Component { timer = null; state = { items: new Array(10).fill(null).map((v, i) => ({ label: 'Item ${i + 1}', strikethrough: false
})) }; onItemClick = index => () => { this.setState(state => ({ ...state, items: state.items.map( (v, i) => index === i ? { ...v, strikethrough: !v.strikethrough } : v ) })); }; render() { return ( <ul> {this.state.items.map((v, i) => ( <MyItem key={i} label={v.label} strikethrough={v.strikethrough} onClick={this.onItemClick(i)} /> ))} </ul> ); } } export default MyList;

Now when you run this app, you'll see the 10 items rendered immediately. Other than this, there are no other changes. You can still click on individual items to toggle their strikethrough state. Once you have this app up and running, make sure the React Developer Tools browser pane is open so that you can select the <MyList> element:

To the right, you can see the state of the selected element. You can actually expand one of the objects in the items array and change its property values:

The label and strikethrough properties of the first object in the items array state were changed. This caused the <MyList> and the first <MyItem> elements to be re-rendered. As expected, the changed state is reflected in the rendered output to the left. This is handy when you need to troubleshoot components that aren't updating their rendered content as they should be. Rather than having to orchestrate some test code within the component, you can simply reach directly into the rendered element's state and manipulate it within the browser.

The one caveat with editing state like this using React Developer Tools is that you can't add or remove items from collections. For example, I can't add a new item to the items array, nor can I add a new property to one of the objects in the array. For this, you need to orchestrate your state in the code, as you did in the example prior to this one.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.69.143