我在我正在创建的一个简单的 React 项目中实现 redux 时遇到了一些困难。澄清一下,这是一个 React 360 WebVR 项目,但我发现它与 React Native 有很多相似之处,我确信它可以工作。
我想做的项目只是通过单击按钮来更改组件的背景颜色。下面是我的代码:
constants.js
export const PICK_COLOR = 'PICK_COLOR';
actions.js
import { PICK_COLOR } from './constants'
export const pickColor = (color) => ({
type: PICK_COLOR,
payload: color
})
reducers.js
import { PICK_COLOR } from './constants';
const initialColor = {
backgroundColor: 'white'
}
export const chooseColor = (state = initialColor, action={}) => {
switch (action.type) {
case PICK_COLOR:
return Object.assign({}, state, {backgroundColor: action.payload})
default:
return state
}
}
index.js
import React from 'react';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
import { chooseColor } from './reducers';
import { pickColor } from './actions';
import {
AppRegistry,
StyleSheet,
Text,
View,
VrButton
} from 'react-360';
const store = createStore(chooseColor);
const mapStateToProps = state => {
return {
backgroundColor: state.chooseColor.backgroundColor
}
}
const mapDisptachToProps = (dispatch) => {
return {
onChooseColor: (event) => dispatch(pickColor(event.target.value))
}
}
class App extends React.Component {
render() {
const { backgroundColor, onChooseColor } = this.props;
return (
<Provider store={store}>
###########################################
I want this to change background color with
the click of a button.
<View style={[styles.panel, backgroundColor: this.props.backgroundColor]}>
###########################################
<VrButton style={styles.greetingBox} onClick={onChooseColor('blue')}>
<Text style={[styles.greeting, {color: 'blue'}]}>
Blue
</Text>
</VrButton>
</View>
</Provider>
);
}
};
const connectedApp = connect(mapStateToProps, mapDisptachToProps)(App);
AppRegistry.registerComponent('App', () => App);
我遇到的问题是冲过终点线。我认为我的一切设置几乎正确,但我无法触发任何状态更改。我感到困惑的部分是如何将我的 onClick 属性处理程序连接到状态更改并传递参数?我混合并匹配了如此多的教程和视频,以至于我现在头晕目眩,而且我还没有完全专注于设置 redux 来有效地排除故障。
根据我收集的信息,我认为我的 mapDispatchToProps
不正确,因为在控制台中我收到 OnChooseColor
不是函数的错误。但我该如何触发改变呢?有人可以帮助指出我哪里出了问题吗?我们将不胜感激。
最佳答案
难道在你的mapStateToProps
中您正在阅读 state.chooseColor.backgroundColor
,但您的商店的形状似乎是 state.backgroundColor
(据我所知 reducers.js
)?
对我来说有点晚了,所以我明天可能会再看一遍! (我会尝试更多的动手实践,而不仅仅是盯着代码!)。但我肯定会尝试通过设置一些断点并查看商店包含的内容来在浏览器中调试您的商店。还有一些方便的浏览器扩展 react和 redux我也会尝试一下! (理论上,它们应该可以更容易地了解 redux 和 React 发生了什么)。
我至少可以自己保证 React 扩展,我大量使用它只是为了能够告诉我正在查看哪个 React 组件(因为 DOM 渲染为 <div>
而不是 <MyComponent>
) !)
编辑:我做了一个与此非常相似的小示例 here !
关于javascript - 如何将我的 mapDispatchToProps 连接到 onClick Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57227340/