【问题标题】:Can I update/set state properties by using map to call a function?我可以通过使用 map 调用函数来更新/设置状态属性吗?
【发布时间】:2019-01-27 20:17:04
【问题描述】:

ReactJS 新手。

我正在尝试构建一个在容器周围移动一些组件的小组件。这个想法是用户点击一个按钮,div的位置发生变化。

我尝试使用Object.keysObject.entries,它们都不起作用。我试图用this.state 创建一个数组,这样我就可以做array.map() 但它不起作用。

constructor(props) {
    super(props);
    this.handleShuffle = this.handleShuffle.bind(this);

    this.state = {
        redLeft: 0,
        redTop: 0,
        blueLeft: 0,
        blueTop: 70
    }
}

getRandomNumber (min, max) {
    return min + (Math.floor(Math.random() * (max-min)))
}

handleShuffle() {
    const min = 0;
    const max = 230;

this.setState({
    redLeft: this.getRandomNumber(min, max),
    redTop: this.getRandomNumber(min, max),
    blueLeft: this.getRandomNumber(min, max),
    blueTop: this.getRandomNumber(min, max),
});
}

据我所知,上面的代码可以工作,但肯定有一种方法可以遍历this.state 中的不同属性并为每个项目调用函数?

【问题讨论】:

标签: javascript arrays reactjs state


【解决方案1】:

如果你的状态只包含你想应用随机数的键,你可以使用 reduce:

this.setState((prevState) => (Object
  .keys({...prevState})
  .reduce((newState, next) => {
    newState[next] = this.getRandomNumber(min, max);
    return newState;
}, {})));

【讨论】:

    【解决方案2】:

    不知道为什么Object.keys 不适合你,但它确实有效。在这里,我遍历this.state 的键并设置该键的状态。

    class Foo extends React.Component {
         constructor(props) {
            super(props);
            
            this.state = {
                redLeft: 0,
                redTop: 0,
                blueLeft: 0,
                blueTop: 70
            }
        }
        
        componentDidMount () {
           this.handleShuffle()
        }
      
        getRandomNumber (min, max) {
            return min + (Math.floor(Math.random() * (max-min)))
        }
      
        handleShuffle() {
            const min = 0;
            const max = 230;
            
            Object.keys(this.state).map(k => {
               this.setState({ 
                 [k]: this.getRandomNumber(min, max)
               })
            })
        }
        
        render () {
          return JSON.stringify(this.state)
        }
    }
    
    ReactDOM.render(<Foo />, document.getElementById('foo'))
    <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="foo"></div>

    【讨论】:

    • 我知道这不是最优雅的解决方案,但请解释否决票。
    最近更新 更多