为什么我的状态没有改变,为什么我对{store.getState()}的引用根本没有出现?

时间:2019-12-30 05:00:06

标签: javascript reactjs react-native redux

我是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 >
  )
}```

3 个答案:

答案 0 :(得分:1)

尝试删除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表示形式。

答案 1 :(得分:1)

实际上redux更改了计数,但是Text视图不听更改。要观察redux的变化,您必须连接组件并制作单独的组件

尝试

import { Provider, useSelector } from 'react-redux'

......

export const Count = () => {
  const count = useSelector(state => {return state && state.count?state.count:0}  );
  return (
    <Text style={{ height: 100, fontSize: 30 }}>
          {count}
   </Text>
  );
};
.....

<View>
        <Count />

.....

答案 2 :(得分:0)

尝试更改代码:

store.dispatch({类型:'NUMBER',有效载荷:6})

进入:

store.dispatch(()=> {return {type:'NUMBER',有效载荷:6}})