After reading here about immutability, I am trying to understand how react is working. I am trying to understand with the help of following 3 components, however its not making sense.
const bla = {a: 1};
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
a: 1,
};
this.onClick = () => this.setState(prevState => ({
a: prevState.a + 1
}));
}
render() {
console.log('Render default');
return <div id="test" onClick = {
this.onClick
} > DOM Updating: {
this.state.a
} < /div>;
}
}
class Test1 extends React.Component {
constructor(props) {
super(props);
this.state = {
a: 1,
};
this.onClick = () => this.setState(prevState => ({
a: 1
}));
}
render() {
console.log('Render 1');
return <div id="test1" onClick = {
this.onClick
} > DOM not updating: {
this.state.a
} < /div>;
}
}
class Test2 extends React.Component {
constructor(props) {
super(props);
this.state = bla;
this.onClick = () => {
const mutating = this.state;
mutating.a = this.state.a + 1;
this.setState(mutating);
};
}
render() {
console.log('Render 2');
return <div id="test2" onClick = {
this.onClick
} > DOM updating with mutation: {
this.state.a
} < /div>;
}
}
ReactDOM.render( < div > < Test / > < Test1 / > < Test2 / > < /div>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
If I inspect div id="test1" it is updating in Chrome dev tool on each click. Want to understand below points:
During on click If I inspect div id="text1" why this is not reflecting in dev tool? Here I am assigning new object in state on each click ({a: 1}). As the link above says
In fact, React.js does not need to have knowledge about what exactly changed. All it needs to know is whether the state changed at all or not.
In Test2 component I am mutating the state however, why dom getting updated on click?
In case of updating nested state since we are updating parent state, does this mean React will think that all others children have changed their values and will re-render all of them even when they aren't changed?
1.) In the console output, you simply see Render 1, because you invoke setState with the static value 1. But in fact, each time you invoke setState with the click, React will set a new (in the sence of new object reference) state for the component, and a new render cycle is triggered.
setState() will always lead to a re-render unless shouldComponentUpdate() returns false. Link
2.) See answer 1. In addition, you have a DOM change, because state changes are merged.
When you call setState(), React merges the object you provide into the current state.
In your Test2 click handler code, mutating will be merged into the current state. It is the same object, but important is, that all its properties (here a property) will be spread into the state, resulting in a new state object.
const mutating = this.state;
mutating.a = this.state.a + 1;
this.setState(mutating);
3.) Let's say you have a Parent component containing all your child components. If you change props or state of Parent, all children will be rerendered by React, unless their shouldComponentUpdate hook returns false or they are PureComponents, whose props or state did not change.
setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. Link
Rerender means, that for each child, React compares the previous and the current version in a Reconciliation step. It only leads to a DOM update, if the child has really changed, otherwise nothing happens. See here for a nice visualization.
Related
I am javascript and React newbie, so I am still a little bit confused by thinking in React concept.
I am trying to make simple object inspector in React.
Here is property row element:
class PropertyRow extends React.Component {
constructor(props) {
super(props);
this.state = {
propertyName: this.props.propertyName,
propertyValue: this.props.propertyValue
};
alert(this.props.propertyName + " evoked in constructor");
}
render() {
return (
<div>{this.props.propertyName} = {this.props.propertyValue}</div>
// <div>{this.state.propertyName} = {this.state.propertyValue}</div>
);
}
}
here in the component PropertyRows I am trying to read all properties of an object dynamically.
class PropertyRows extends React.Component {
constructor(props) {
super(props);
this.createProRows = this.createProRows.bind(this);
}
createProRows(obj) {
const propArr = [];
for (const key of Object.keys(obj)) {
const val = obj[key];
propArr.push(<PropertyRow propertyName={key} propertyValue={val} />);
}
return propArr;
}
render() {
return <div>{this.createProRows(this.props.obj)}</div>;
}
}
And here I test this marvelous code
class Express extends React.Component {
constructor(props) {
super(props);
this.state = {
soldiers: 0,
captain:'John Maverick'
};
this.doClick = this.doClick.bind(this);
}
doClick() {
const obj = {
soldiers: this.state.soldiers + 1,
country:'Australia' //add new property
};
this.setState(obj);
}
render() {
return (
<div onClick={this.doClick}>
<PropertyRows obj={this.state} />
</div>
);
}
}
ReactDOM.render(<Express />, document.getElementById("root"));
When you click on the text, you will see incrementing "soldiers" property by one. The code is buggy and I do not understand why, or perhaps I do, but I have not absolutely no idea, what how to solve it in React metalanguage.
I would expect, that dynamically created array of <PropertyRow propertyName={key} propertyValue={val}/> would be nice way to browse object properties. But it seems, that the rendered HTML DOM objects are not destroyed and recreated. They are mysteriously reattached, when the new object in the doClick function is to be expressed.
Furthermore
When create another object in doClick, the property obj.captain is still there (in the browser window), probably because the underlying HTML DOM elements are not destroyed. Adding new property country: 'Australia' seems to work OK.
When I call <PropertyRow propertyName={key} propertyValue={val}/> the second time I would expect, that constructor would be fired, because it is created and pushed in the new array. But it is not. It is fired only for the new property country: 'Australia'
It seems, that I have to somehow destroy rendered HTML DOM elements in order to force react to recreate them. But how?
Or is there another way?
I deeply apologize for this long text. I hope it's not so complicated to read.
Thanx
delete obj.captain doesn't do anything because there's no captain key in obj. captain key exists in this.state, and deleting it from it is discouraged because React state is conventionally immutable.
The use of this.state together with this.setState may potentially result in race condition, state updater function should be used instead.
It should be:
doClick() {
this.setState(state => ({
soldiers: state.soldiers + 1,
country:'Australia',
captain: undefined
}));
}
The problem with PropertyRow is that it processes props once in constructor. PropertyRow constructor is fired only once because the component has been already mounted and now it is only updated on new props (here's illustrative diagram of React lifecycle hooks).
If a state is supposed to derive from received props, getDerivedStateFromProps hook should be used, it maps a state from props before initial render and next updates. In this case a state is not needed because state properties and props don't differ. It's enough to have:
class PropertyRow extends React.Component {
render() {
return (
<div>{this.props.propertyName} = {this.props.propertyValue}</div>
);
}
}
And PropertyRow could be rewritten as functional component because it doesn't benefit from being a class.
Good Afternoon,
I have a React component that is dynamically rendered in reponse to an API call. I have set the value of one of the elements to a state within the component. During an onClick function (minusOne) this value is supposed to change.
The value is initially rendered successfully based on the state, the function does indeed change the state, however the rendered element stays the same despite the state changing. Does anyone have any ideas of why this might be the case?
If you have any questions, please ask away!
export class Cart extends React.Component {
constructor(props) {
super(props);
this.state={
quantities: []
};
this.minusOne = this.minusOne.bind(this);
}
minusOne(i) {
var self = this;
return function() {
let quantities = self.state.quantities;
if (quantities[i] > 1) {
quantities[i] --;
}
self.setState({
quantities
})
}
}
componentDidMount() {
let cart = this.props.cartTotals;
this.setState({
cart
});
if(cart.lines) {
let cartTotal = [];
let quantities = [];
for (var i = 0; i < cart.lines.length; i++) {
if(cart.lines[i]) {
quantities.push(cart.lines[i].quantity);
}
}
//Initial setting of state
this.setState({
quantities
})
Promise.all(
cart.lines.map(
(cart, i) => axios.get('http://removed.net/article/' + cart.sku)
)
).then(res => {
const allCartItems = res.map((res, i) => {
const data = res.data;
return(
<div key={i} className="cart-item-container">
<img className ="cart-item-picture" src={data.image} name={data.name} />
<div className="cart-item-description">
<p>{data.name}</p>
<p>{data.price.amount} {data.price.currency}</p>
</div>
<div className="cart-item-quantity">
<button onClick={this.minusOne(i)} name="minus">-</button>
//This is the troublesome element
<p className="cart-current-quantity">{this.state.quantities[i]}</p>
<button name="plus">+</button>
</div>
</div>
)
})
this.setState({
allCartItems
})
})
}
}
render() {
return (
{this.state.allCartItems}
);
}
}
Thanks for reading! Any advice will be helpful.
There are two issues:
First, you need to render (including where the onClick is) in render(). ConponentDidMount is only called once and supposed to perform initialization but not render.
Then, there is a problem in minusOne:
quantities points to this.state.quantities. So you are changing the old state, React looks at both the old state and the new one, sees there is no change, and dodesn't render, although the values have changed.
If you will copy this.state.quantities to a new array, like:
newQ = this.state.quantities.slice(0, -1);
Then modify newQ, then do
this.setState({ quantities: newQ });
It should work.
I think you don't need to return a function at minusOne(i) method. Just update the state is enough. You should change the array by specific id.
let quantities = self.state.quantities;
let mutatedQuantities = quantities.map((el, index) => {
return (index === i) ? el - 1 : el;
})
this.setState({quantities: [...mutatedQuantities]})
--- edited ---
I deleted everything I wrote before to make it more concise.
Your problem is that you assign what you want to render to a variable in componentDidMount. This function does only get called once, hence you asigne the variable allCartItems only once. The setState function does not have any effect because it does not trigger componentDidMount and therefore your variable allCartItems does not get reassigned.
What can you do? Well you can do a lot of stuff to enhance your code. First I will let you know about how you can solve your problem and then give you some further improvements
To solve the problem of your component not updating when you call setState you should move your jsx to the render Method. In the componentDidMount you just get all the data you need to render your component and once you have it you can set a flag for example like ready to true. Below you can see an example of how your code could look like.
import React from 'react';
class Cart extends React.Component {
constructor(props) {
super(props);
this.state = {
carts: null,
ready: false,
};
}
componentDidMount() {
fetch('www.google.com').then((carts) => {
this.setState({
carts,
ready: true,
});
});
}
render() {
const myCarts = <h2> Count {this.state.carts} </h2>;
return (
{
this.state.ready
? myCarts
: <h2> Loading... </h2>
}
);
}
}
I made you a demo with a simple counter with some explanations of your case and how you can make it work. You can check it out codesandbox. In the NotWorkingCounter you can see the same problem as in your component of the variable not being updated. In the WorkingCount you can see an example where I implemented what a I wrote above with waiting until your data has arrived and only then render it.
Some more suggestions concerning code:
Those two syntaxes below are identical. One is just a lot more concise.
class Cart extends React.Component {
constructor(props) {
super(props);
this.state = {
carts: null,
ready: false,
};
}
}
class Cart extends React.Component {
state = {
carts: null,
ready: false,
}
}
I would suggest to use arrow function if you want to bind your context. Below you can see your example simplified and an example on how you can achieve the same thing with less syntax.
export class Cart extends React.Component {
constructor(props) {
super(props);
this.minusOne = this.minusOne.bind(this);
}
minusOne(i) {
///
}
}
export class Cart extends React.Component {
constructor(props) {
super(props);
}
minusOne = (i) => {
/// minus one function
}
}
Your minusOne could also be rewritten if you use arrow functions and be a lot smaller, something in the area of
minusOne = (i) => (i) => {
let quant = self.state.quantities[i];
if(quant > 1) {
this.setState({
quantities: quant-1,
})
}
}
In your componentDidMount you call this.setState twice. Every time you call this function your component gets rerender. So what happens in your component is when your mount your component it gets rendered the first time, once it is mounted componentDidMount gets called, in there you call this.setState again twice. This means your component get's rendered in the best case three times before the user sees your component. If you get multiple promises back this means your rerender your state even more. This can create a lot of load for your component to cope with. If you rerender every component three times or more you end up having some performance issues once your application grows. Try to not call setState in your componentDidUpdate more than once.
In your case your first call to setState is totally unnecessary and just creates load. You still have access to quantities in your promise. Just call setState once at the end of your promise.then() with both elements.
In the example below you are using the index i as a key. This is not a good case practice and react should also log you at least a warning in the console. You need to use a unique identifier which is not the index. If you use the index you can get sideeffects and weird rendering which is difficult to debut. Read more on it here
then(res => {
const allCartItems = res.map((res, i) => {
const data = res.data;
return(
<div key={i} className="cart-item-container">
Another suggestion is to replace all var with const or let, as var exposes your variable to the global scope. If you don't understand what that means read this.
Last but not least have a look at object deconstruction. It can help you to clean up your code and make it more resistant to unwanted sideffects.
Check the code here
jsfiddle
I wish to update the value property of individual item from the Child component. But as props are immutable and don't trigger re-render the code doesn't work. One way I know to make this work is pass a function from GrandParent to Parent and then to Child and use it to update state of GrandpParent. This will trigger re-render in the Child component. But this also causes re-render of GrandParent, Parent and other siblings of Child component.
// comment
Is there a better way to do this, this doesn't seem optimal to me.
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleClick = this.handleClick.bind(this)
}
handleClick(e) {
this.props.handleIncrement(e.currentTarget.dataset.key)
}
render() {
return (
<div>
<span>{this.props.item.value}</span>
<button data-key={this.props.item.key} onClick={this.handleClick}>inc</button>
</div>
);
}
}
class Parent extends React.Component {
render() {
return (
<div>
{
this.props.list.map((item) => <Child item={item} handleIncrement={this.props.handleIncrement} />)
}
</div>
);
}
}
class GrandParent extends React.Component {
constructor(props) {
super(props);
this.state = {
list: [
{
key: 'one',
value: 1
},
{
key: 'two',
value: 2
},
{
key: 'three',
value: 3
}
]
};
this.handleIncrement = this.handleIncrement.bind(this)
}
handleIncrement(key) {
this.setState({
list: this.state.list.map((l) => {
if (l.key === key) {
return {key: l.key, value: l.value + 1}
}
return l
})
})
}
render() {
return (<Parent list={this.state.list} handleIncrement={this.handleIncrement} />);
}
}
React.render(<GrandParent />, document.getElementById('container'));
You have to pass the handler from the Grand parent and call this handler whenever you wanted to increment. Read about coupling and cohesion for theoretical background.
React is based on the concept of unidirectional data flow. This means that your are passing data down to other components who receive it as props and render it, or passing it down to another sub component.
However, sometimes we want a child component to let a parent component that something happened. To solve this, we use callback. Callbacks are functions that we can pass as props to a child component, so he can use them we something happens. A classic example is to pass an onClick handler to a child component that has a button. Then, when the button is pushed the child component calls it like this:
this.props.onClick()
letting the parent know that the button was clicked. This will work for yor example too. Create a function in the GrandParent component that knows how to increment the value.
incrementValue = (idx) => {
// Copy the list to avoid mutating the state itself.
let newList = this.state.list.slice();
newList[idx].value += 1;
this.setState({list: newList});
}
Then pass this function as callback
<Parent onClick={this.incrementValue}/>
Then bind it to the button click like this:
<button onClick={this.props.onClick}>inc</button>
Read this to learn more about state and props in React.
In following code cityNameLength is a number and represent the length of the name of one city.
My goal is to render multiple elements based on cityNameLength value.
So if cityNameLength is equal to 5 I'd like to have 5 span elements.
This is what I've have:
class myCitiesClass extends Component {
constructor(props) {
super(props);
this.state = {cLength: 0};
this.setState({ cLength: this.props.cityNameLength });
}
renderDivs() {
var products = []
var cNameLength = this.state.cLength
for (var p = 0; p < cNameLength; p++){
products.push( <span className='indent' key={p}>{p}</span> );
}
return products
}
render() {
return (
<View>
<Text>City name length: {this.props.cityNameLength}</Text>
<View>{this.renderDivs()}</View>
</View>
);
}
}
This is the error I get:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.
There are two ways you can do this. If you want to render the spans before the component is mounted, get rid of the setState and just do this in the constructor:
this.state= {cLength: this.props.cityNameLength };
If you want the component to mount first - then remove the setState from the constructor and move it into componentDidMount():
componentDidMount() {
this.setState({ cLength: this.props.cityNameLength });
}
You cannot use this.setState in the constructor. And fortunately, you don't need to. State could be set to the proper value right in the assignment:
constructor(props) {
super(props);
this.state = { cLength: this.props.cityNameLength };
}
However, this code is not good too. Assigning state from props is not necessarily the mistake, but you have to know well what you're doing and why (thing is that props could be changed from the top level component at any time, and you will have to keep state in sync with overridden componentWillReceiveProps() to make your component work right). If you doubt you do, you should avoid it.
In your case it should be easy as you don't need state at all. Remove constructor, and use this.props.cityNameLength instead of this.state.cLength.
And when you modify state from componentDidMount() you are supposed to know very well what you're doing (because you're triggering another render right after your component is just rendered - why?). In 99% of cases it's the mistake. Not that fatal as doing so in componentDidUpdate, though.
In this example, when I try to update the state during the componentDidUpdate life cycle callback, I get a too much recursion error. How should I be updating the state?
import React from 'react';
class NotesContainer extends React.Component {
constructor(props) {
super(props);
this.state = { listOfShoppingItems: [] };
}
componentDidUpdate(nextProps, nextState) {
let newShoppingItems = this.calculateShoppingItems();
this.setState({ listOfShoppingItems: newShoppingItems });
}
calculateShoppingItems() {
let shoppingItemsCart = []
if (this.props.milk < 3) {
let value = "Buy some milk";
shoppingItemsCart.push(value);
}
if (this.props.bread < 2) {
let value = "Buy some bread";
shoppingItemsCart.push(value);
}
if (this.props.fruit < 10) {
let value = "Buy some fruit";
shoppingItemsCart.push(value);
}
if (this.props.juice < 2) {
let value = "Buy some juice";
shoppingItemsCart.push(value);
}
if (this.props.sweets < 5) {
let value = "Buy some sweets";
shoppingItemsCart.push(value);
}
return shoppingItemsCart;
}
render() {
return (
<div>
Etc...
</div>
);
}
}
export default NotesContainer;
componentDidUpdate is triggered when either the props or the state has changed. If you change the state in this method, you are causing an infinite loop (unless you implement shouldComponentUpdate).
It looks like your state changes when you receive new props, therefore componentWillReceiveProps seems a good place. From the docs:
Invoked when a component is receiving new props. This method is not called for the initial render.
Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.