我可以通过使用map来调用函数来更新/设置状态属性吗?

时间:2019-01-27 20:17:04

标签: javascript arrays reactjs state

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中的不同属性并为每个项目调用函数吗?

2 个答案:

答案 0 :(得分:0)

如果您的状态仅包含要将随机数应用于以下项的键,则可以使用reduce:

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

答案 1 :(得分:-1)

不确定def windowz(data, size): start = 0 while start < len(data): yield start, start + size start += (size // 2) def segment_dap(x_train,window_size): segments = np.zeros(((len(x_train)//(window_size//2))-1,window_size,11)) i_segment = 0 i_label = 0 for (start,end) in windowz(x_train,window_size): if(len(x_train[start:end]) == window_size): segments[i_segment] = x_train[start:end] i_segment+=1 return segments X = np.loadtxt("THEdataset.txt", delimiter=" ") train_x, test_x = train_test_split(X, test_size=0.20, random_state=42) print(X.shape) print(train_x.shape) print(test_x.shape) input_width = 2 x_train = segment_dap(train_x,input_width) x_test = segment_dap(test_x,input_width) print(x_train.shape) print(x_test.shape) def train_model(): input_layer = Input(shape=(2,11)) # adapt this if using `channels_first` image data format x = Conv1D(filters=11, kernel_size=2, strides=1, activation='relu', padding='same')(input_layer) x = Conv1D(filters=11, kernel_size=2, strides=1, activation='relu', padding='same')(x) x = Conv1D(filters=11, kernel_size=2, strides=1, activation='relu', padding='same')(x) x = Conv1D(filters=11, kernel_size=2, strides=1, activation='relu', padding='same')(x) x = Conv1D(filters=11, kernel_size=2, strides=1, activation='relu', padding='same')(x) x = Conv1D(filters=11, kernel_size=2, strides=1, activation='relu', padding='same')(x) decoded = Conv1D(filters=11, kernel_size=2, strides=1, activation='relu', padding='same')(x) autoencoder = Model(input_layer, decoded) autoencoder.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) hist=autoencoder.fit(x_train,x_train, epochs=5, batch_size=128, validation_split=0.2, verbose = 2) avg = np.mean(hist.history['acc']) print('The Average Training Accuracy is', avg) 为何对您不起作用,但确实起作用。在这里,我遍历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'))