我正在尝试使用redux从API中获取数据以进行本机反应,但未进行获取。该API基于必须提取的颜色,它只在屏幕上显示更改按钮,而在单击后不更改backgroundColor
这是代码:
App.js
import React, {Component} from 'react';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import ReduxThunk from 'redux-thunk';
import reducers from "./reducers";
import BoxCon from './container/box-container';
class App extends Component {
render() {
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return (
<Provider store={store}>
<BoxCon />
</Provider>
);
}
}
export default App;
container / box-container.js
import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {connect} from "react-redux";
import * as actionCreators from "../action/index.js"
import Box from '../component/box.js';
//import { actionCreators } from 'redux';
class BoxCon extends Component{
render(){
return(
<Box handleClick={this.props.loadColor} color={this.props.color} />
)
}
}
const mapStatetoProps=(state)=>{
return state
};
export default connect (mapStatetoProps, actionCreators)(BoxCon);
component / box.js
import React, {Component} from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
export default class Box extends Component{
render(){
return(
<View style={styles.container}>
<View style={{backgroundColor:'${this.props.color}'}}>
<TouchableOpacity onClick={()=>{this.props.handleClick()}} style={styles.button}>
<Text>
Change Color
</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
reducers / index.js
const INITIAL_STATE ={
color:"red"
}
const mainReducer=(state=INITIAL_STATE,action)=>{
if(action.type==="CHANGE_COLOR"){
return{
...state,
color:action.color
}
} else{
return{
state
}
}
}
export default mainReducer;
action / index.js
import axios from "axios";
export function loadColor(){
return(dispatch) => {
return axios.get("http://www.colr.org/json/color/random").then((response)=>{
dispatch(changeColor("#"+response.data.new_color));
}) .catch((error) => {
console.log(error);
});
}
}
export function changeColor(color){
return{
type:"CHANGE_COLOR",
color:color
}
}
答案 0 :(得分:0)
这可能是因为您未指定有效负载。
更改:
if(action.type==="CHANGE_COLOR"){
return{
...state,
color:action.color
}
}
...
export function changeColor(color){
return{
type:"CHANGE_COLOR",
color:color
}
}
到
if(action.type==="CHANGE_COLOR"){
return{
...state,
color:action.payload
}
}
...
export function changeColor(color){
return{
type:"CHANGE_COLOR",
payload:color
}
}
我认为它会起作用。