I am trying to make a simple page with React and JSX that will generate a couple of input fields which can be erased by clicking a button.
I am currently storing an empty array within the Page's state, which gets updated by the addItems function.
For some reason, I am not able to clear the array with my clear function. I understand that setState
is asynchronous, but my array never gets updated and never disappears.
"use strict";
function Node(props) {
return(<div>
<input type="text" placeholder="input here"></input>
</div>);
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: [],
thresh: 5,
del: "Delete",
};
this.addItem = this.addItem.bind(this);
this.clear = this.clear.bind(this);
}
addItem = (index, array) => {
if (index == this.state.thresh) {
this.setState((state, props) => ({
arr: array,
}));
return;
}
index++;
array.push(<Node key={index} />);
this.addItem(index, array);
};
clear = newArr => {
this.setState({
arr: newArr,
}, () => { console.log(this.state.arr) });
};
render() {
return(<div id="wrapper onClick={() => {this.addItem(0,[])}}>
<div id="fields">
{this.state.arr}
</div>
<button onClick={() => {this.clear([])}}>{this.state.del}</button>
</div>
}
}
ReactDOM.render(<Page />, document.getElementById("root"));
I am expecting that when I hit the delete button the array will be overwritten with an empty array but this does not happen. What could I be doing wrong?
I am trying to make a simple page with React and JSX that will generate a couple of input fields which can be erased by clicking a button.
I am currently storing an empty array within the Page's state, which gets updated by the addItems function.
For some reason, I am not able to clear the array with my clear function. I understand that setState
is asynchronous, but my array never gets updated and never disappears.
"use strict";
function Node(props) {
return(<div>
<input type="text" placeholder="input here"></input>
</div>);
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: [],
thresh: 5,
del: "Delete",
};
this.addItem = this.addItem.bind(this);
this.clear = this.clear.bind(this);
}
addItem = (index, array) => {
if (index == this.state.thresh) {
this.setState((state, props) => ({
arr: array,
}));
return;
}
index++;
array.push(<Node key={index} />);
this.addItem(index, array);
};
clear = newArr => {
this.setState({
arr: newArr,
}, () => { console.log(this.state.arr) });
};
render() {
return(<div id="wrapper onClick={() => {this.addItem(0,[])}}>
<div id="fields">
{this.state.arr}
</div>
<button onClick={() => {this.clear([])}}>{this.state.del}</button>
</div>
}
}
ReactDOM.render(<Page />, document.getElementById("root"));
I am expecting that when I hit the delete button the array will be overwritten with an empty array but this does not happen. What could I be doing wrong?
Share Improve this question edited Jun 27, 2019 at 21:56 GavinBarrett asked Jun 27, 2019 at 20:50 GavinBarrettGavinBarrett 191 gold badge1 silver badge4 bronze badges 4- It is the clear function executed when you click the button? – Josep Vidal Commented Jun 27, 2019 at 21:00
-
"...but this does not happen" What evidence do you have that this isn't working the way it should? As far as I can tell, your
clear()
function looks correct. On the other hand, youraddItem()
function looks strange, especially because you are pushing to an array after you callsetState()
. I suggest that you install the React Developer Tools addon for your browser. This will allow you to directly inspect your ponent's state to see if it is working correctly. This is more reliable thanconsole.log()
. – Code-Apprentice Commented Jun 27, 2019 at 21:35 - @JosepVidal yes the function executes. – GavinBarrett Commented Jun 27, 2019 at 21:58
- @Code-Apprentice the callback function prints an array with elements inside of it. In regards to addItem, I forgot to include a line which I've just added. – GavinBarrett Commented Jun 27, 2019 at 21:59
5 Answers
Reset to default 1clear function looks alright, altho when i tried to run your code, it popped up multiple errors and a typo. Also addItem method looks weird to me... you are not pushing nodes into state.arr instead your are pushing it into empty array all the time.
here i tried to clean up code a bit, and even though functionality might not be what you want to have, it proves the concept that cleanup is the first thing you need to do :)
in snippet below clear function works fine and it's not modified.
function Node(props) {
return(<div>
<input type="text" placeholder="input here"></input>
</div>);
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: [],
thresh: 5,
del: "Delete",
};
this.addItem = this.addItem.bind(this);
this.clear = this.clear.bind(this);
}
addItem(index, array) {
var newArr = JSON.parse(JSON.stringify(this.state.arr))
newArr.push(<Node />)
this.setState({
arr: newArr
});
}
clear(newArr) {
this.setState({
arr: newArr,
}, () => { console.log(this.state.arr) });
}
render() {
return(<div>
<div id="wrapper" onClick={() => {this.addItem(0,[1])}}>asdasd</div>
<div id="fields"> {this.state.arr} </div>
<button onClick={() => {this.clear([])}}>{this.state.del}</button>
</div>)
}
}
ReactDOM.render(<Page />, document.getElementById("root"));
Try building / adding your logic on top of code here and it will work.
`
clear = () => {
this.setState({
arr: [],
}, () => { console.log(this.state.arr) });
setTimeout(() => { console.log("o/p", this.state.arr); }, 3000);
};
` It will work try to put timer function. it works Acyncronasly.
Your clear method should look like this:
clear = () => {
this.setState({
arr: [],
});
};
your click handler in button :
<button onClick={this.clear}>{this.state.del}</button>
and if you use arrow functions you don't have to bind them in constructor, you can remove bind's
I'm noticing quite a few problems here but one thing i see is your delete button is wrapped in the container that adds. so every time you click delete, it also will add to the array.
on another note though, this code doesn't seem functional. The way its written looks like it will never add anything to the state array so i'm not sure how you are seeing anything other than an empty array.
I believe you're trying to acplish something like this:
function Node(props) {
return (<div>
<input type="text" placeholder="input here"></input>
</div>);
}
export default class ClearTest extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
arr: [<Node key={1} />],
thresh: 5
};
}
addItem = () => {
const { arr, thresh } = this.state;
if (arr.length < thresh)
this.setState({ arr: [...(arr), <Node key={arr.length + 1} />] })
};
clear = () => {
this.setState({ arr: [] }, () => { console.log(this.state.arr) });
};
public render() {
return (
<div id="wrapper">
<div id="fields">
{this.state.arr}
</div>
<button onClick={this.clear}>Delete</button>
<button onClick={this.addItem}>Add</button>
</div>
);
}
}
this will move the add to a button and allow up to 5 inputs to be added. Clicking delete will remove them all.
You can try to reset it using a custom reset function:
import React, { Component } from 'react';
const getDefaultState = () => ({
myArray: [],
});
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = { ...getDefaultState() };
}
ponentDidMount() {
this.setState({ myArray: [1, 2, 3] })
}
resetState = () => {
this.setState({ ...getDefaultState() });
};
render() {
return (
<div onClick={this.resetState}>
{JSON.stringify(this.state.myArray)}
</div>
);
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745254094a4618852.html
评论列表(0条)