gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:44:50 25 4
gpt4 key购买 nike

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

最佳答案

实际上 redux 已经改变了 count 但 Text view 不听变化。要观察 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 />

.....

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com