如何自动检查每个状态值和setState

时间:2019-01-21 07:14:32

标签: reactjs

如何检查每个状态是否有值,然后合并所有值?

class App extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			inputvalue : '',
      allval: ''
		}
	}
  
  onChangeOfInput =(name,value) =>{
  	this.setState({
			[name]: value
		});
  }
  
  getValues = () =>{
  	console.log(this.state);
    if(this.state.Title1) {
      this.setState({
       	allval: this.state.allval+this.state.Title1
      });
    }
  }

	render() {
		return (
			<div className="hello">
				<Input onChangeOfInput={this.onChangeOfInput}
					placeholder="Title 1" name="Title1" />
				<br/>
				<Input placeholder="Title 2" name="Title2"  onChangeOfInput={this.onChangeOfInput} />
				<br/>
				<Input placeholder="Title 3" name="Title3"  onChangeOfInput={this.onChangeOfInput}/>
				<br/>
				<Input placeholder="Title 4" name="Title4"  onChangeOfInput={this.onChangeOfInput}/>
				<br/>
				<button onClick={this.getValues}>Get value</button>
				
			</div>
		)
	}
}

class Input extends React.Component  { 
	constructor(props) {
		super(props)
		this.state = {
			inputvalue: ''
		}
	}

	handleChange(e) {
  
		this.setState({
			inputvalue: e.target.value
		});
    this.props.onChangeOfInput(this.props.name,e.target.value)
	}

	render() {
		return (
			<input 
				type="text" 
				placeholder={this.props.placeholder} 
				value={this.state.inputvalue} 
				onChange={this.handleChange.bind(this)}
				/>
		)
	}
}

ReactDOM.render(<App />, document.querySelector("#app"))
<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="app"></div>

jsfiddle:https://jsfiddle.net/vxm2ojLz/

问题出在这里,我需要检查每个值state.Title1state.Title2state.Title3state.Title4,如果它们不为空,那么我想合并所有值如果它不为空并将组合的值分配给allVal,如何将所有值组合到allval?谢谢

4 个答案:

答案 0 :(得分:2)

您需要做这样的事情。

getValues = () => {
    console.log(this.state);
    let combinedString = "";
    Object.keys(this.state)
        .map( igKey => {
        if(this.state[igKey] != "" && igKey.includes('Title')){
           combinedString = combinedString +''+ this.state[igKey];
           return combinedString
          }
        });
    this.setState({allval:combinedString})
    console.log(combinedString);
  }

工作小提琴https://jsfiddle.net/2nhc6drm/

希望这会有所帮助!

答案 1 :(得分:1)

尝试像这样处理getValues

getValues = () =>{
    console.log(this.state);
    let result = [];
    Object.keys(this.state).forEach(key => {
        if (key.includes('Title') && this.state[key]) result.push(`${key}: ${this.state[key]}`);
    })
    this.setState({
        allval: result.join('; ')
    })
  }

答案 2 :(得分:1)

请更新 getValues 方法:-

为方便起见,它将忽略键 allval inputval

   getValues = () => {
    let allval = ''
   for(let key of Object.keys(this.state)){

     if(key==='allval' || key==='inputval'){
       continue;
     }
     else{
       let value=this.state[key];
       console.log(value);
       if(value===''){

       }
       else{
           allval=allval+value;
       }
       console.log(allval);
     }
   }
   this.setState({allval:allval})
  }

工作沙盒:-https://codesandbox.io/s/vqoxo9w1wy

希望这会有所帮助

干杯!

答案 3 :(得分:1)

我建议使用services: web: build: ./php container_name: php_web volumes: - php-volume:/var/www/html/ ports: - "8100:80" stdin_open: true tty: true python: build: ./python volumes: - ./product:/user/src/app ports: - "5000:5000" volumes: php-volume: 组合值,并使用功能性的reduce避免双重状态变化:

setState
class App extends React.Component {
  state = {
    allVal: '',
    title1: '',
    title2: ''
  }

  getValues = (prevState, name, newVal) => {
    return Object.keys(prevState)
    .reduce((acc, key) => {
      if (key === 'allVal') return acc;
      if (key === name) return acc + newVal;
      return acc + prevState[key];
     }, '')
  }
  
  handleChange = ({ target: { name, value } }) => {
    this.setState(prevState => ({
      [name]: value,
      allVal: this.getValues(prevState, name, value)
    }))
  }

  render(){
    const { title1, title2, allVal } = this.state;
  
    return (
      <div>
        <input name="title1" onChange={this.handleChange} value={title1} /><br />
        <input name="title2" onChange={this.handleChange} value={title2} /><br />
        allVal: <span>{allVal}</span>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));