我试图围绕如何在传递给组件的道具用于改变应用程序状态的情况下如何使用redux。
我有一个工作示例here。
let Input = ({handleChange}) => (
<input type="text" onChange={handleChange('mySpecialInput')} />
)
let Text = ({message, color}) => (
<span style={{color}}>{message}</span>
)
let App = ({message, color, handleChange}) => (
<div>
<Text message={message} color={color} /> <br />
<Input handleChange={handleChange} />
</div>
)
class ConnectedApp extends React.Component {
constructor(props) {
super(props)
this.state = {
color: 'orange',
message: 'Hello World'
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(id) {
return (event) => {
console.log(id)
if (id === 'mySpecialInput') {
this.setState({'color': event.target.value})
}
}
}
render() {
return (
<App
message={this.state.message}
color={this.state.color}
handleChange={this.handleChange} />
)
}
}
ReactDOM.render(
<ConnectedApp/>,
document.getElementById('react_example')
);
如何使用redux来处理这样简单的事情?
答案 0 :(得分:2)
以上是使用redux构建的代码!
let {createStore} = Redux
let {connect, Provider} = ReactRedux
// React component
let Input = ({handleChange}) => (
<input type="text" onChange={handleChange('mySpecialInput')} />
)
let Text = ({message, color}) => (
<span style={{color}}>{message}</span>
)
let App = ({message, color, handleChange}) => (
<div>
<Text message={message} color={color} /> <br />
<Input handleChange={handleChange} />
</div>
)
// Action
const CHANGE_COLOR = 'CHANGE_COLOR'
function changeColorAction(color) {
return {
type: CHANGE_COLOR,
color
}
}
// Reducer
function reducer(state = {color: "#ffa500"}, action) {
let count = state.count
switch (action.type) {
case CHANGE_COLOR:
return { color: action.color }
default:
return state
}
}
// Store
let store = createStore(reducer)
// Map Redux state to component props
function mapStateToProps(state) {
return {
color: state.color,
message: "Hello World"
}
}
function changeColorDispatcher (dispatch) {
return (id) => {
return (event) => {
if (id === 'mySpecialInput') {
return dispatch(changeColorAction(event.target.value))
}
}
}
}
// Map Redux actions to component props
function mapDispatchToProps(dispatch) {
return {
handleChange: changeColorDispatcher(dispatch)
}
}
// Connected Component
let ConnectedApp = connect(
mapStateToProps,
mapDispatchToProps
)(App)
ReactDOM.render(
<Provider store={store}>
<ConnectedApp/>
</Provider>,
document.getElementById('react_example')
);
答案 1 :(得分:-1)
您可以单独连接每个组件,而不是在顶级组件上使用connect()
并在层次结构树中传递道具。
这将更方便。
See a working example!