我是React和Redux的新手,遇到了麻烦。下面的代码不会将我的状态更新为我所希望的7,并且该区域不呈现任何内容,甚至没有默认值。

我已经尝试了几天来对此进行研究。

任何帮助表示赞赏。

谢谢。

import React from 'react';
import { Text, Button, View } from 'react-native'
import { createStore } from 'redux'
import { Provider } from 'react-redux'


// Define the initial state of our store
const initialState = { count: 5 }

// Define a reducer
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'NUMBER':
      return { ...state, count: 7 }, console.log("test2", state.count, action.payload);
    default:
      return state, console.log("test");
  }
};


// Create a store, passing our reducer function and our initial state
const store = createStore(reducer)

/// We're done! Redux is all set up. Here's how we can use it:

// Calling `store.getState()` returns our state object
export default function App() {

  return (
    <Provider store={store}>
      <View>
        <Text style={{ height: 100, fontSize: 30 }}>
          {store.getState()}
        </Text>
        <Button
          title='Button'
          onPress={() => { store.dispatch({ type: 'NUMBER', payload: 6 }) }}
        />
      </View>
    </Provider >
  )
}```

最佳答案

尝试删除您的console.log语句。我认为他们正在阻止状态更新:

return { ...state, count: 7 }, console.log("test2", state.count, action.payload);


和这里

return state, console.log("test");


如果您想登录,请在返回之前进行操作:

console.log({ state, action })
return state


尝试JSON.stringify(store.getState())呈现状态的JSON表示形式。

关于javascript - 为什么我的状态没有改变,为什么我对{store.getState()}的引用根本没有出现?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59525920/

10-10 22:11
查看更多