Learned how to modify objects in a component's state.

This commit is contained in:
Robbie Antenesse 2016-09-22 08:25:49 -06:00
parent 1e2758f3d3
commit 9a90108fe6
2 changed files with 27 additions and 5 deletions

View File

@ -8,6 +8,7 @@ export class Dictionary extends React.Component {
super(props); super(props);
this.state = { this.state = {
dictionary: this.props.reference,
name: this.props.reference.name, name: this.props.reference.name,
description: this.props.reference.description, description: this.props.reference.description,
createdBy: this.props.reference.createdBy, createdBy: this.props.reference.createdBy,
@ -56,17 +57,19 @@ export class Dictionary extends React.Component {
}, () => console.log(this.state.words)); }, () => console.log(this.state.words));
} }
changeTestWord() { changeNameAgain() {
this.setState( let updateDictionary = this.state.dictionary;
words[0].name: 'cool' updateDictionary.name = 'something else again'
); this.setState({
dictionary: updateDictionary
})
} }
render() { render() {
return ( return (
<div> <div>
<h1 id="dictionaryName"> <h1 id="dictionaryName">
{this.state.name} {this.state.dictionary.name}
</h1> </h1>
<h4 id="dictionaryBy"> <h4 id="dictionaryBy">
@ -84,6 +87,10 @@ export class Dictionary extends React.Component {
action={() => this.addTestWord()} action={() => this.addTestWord()}
label='Add a Test Word' /> label='Add a Test Word' />
<Button
action={() => this.changeNameAgain()}
label='Change Name Again' />
<Button <Button
action={() => { action={() => {
this.setState({isComplete: !this.state.isComplete}) this.setState({isComplete: !this.state.isComplete})

View File

@ -6,6 +6,7 @@ import ReactDOM from 'react-dom';
import {Header} from './components/Header'; import {Header} from './components/Header';
import {NewWordForm} from './components/NewWordForm'; import {NewWordForm} from './components/NewWordForm';
import {Button} from './components/Button';
import {Dictionary} from './components/Dictionary'; import {Dictionary} from './components/Dictionary';
class Lexiconga extends React.Component { class Lexiconga extends React.Component {
@ -42,11 +43,25 @@ class Lexiconga extends React.Component {
// this.addTestWord(); // this.addTestWord();
} }
changeDictionaryName() {
// To change elements within the dictionary object, you can set it to
// a variable, manipulate the variable, then use setState() to set
// the object equal to the changed variable.
let updateDictionary = this.state.currentDictionary;
updateDictionary.name = 'something else'
this.setState({
currentDictionary: updateDictionary
})
}
render() { render() {
return ( return (
<div> <div>
<Header /> <Header />
<NewWordForm reference={this.state.currentDictionary} /> <NewWordForm reference={this.state.currentDictionary} />
<Button
action={() => this.changeDictionaryName()}
label='change name' />
<Dictionary reference={this.state.currentDictionary} /> <Dictionary reference={this.state.currentDictionary} />
</div> </div>
); );