所以我正在尝试在react-redux存储中设置一个计时器。我的动作已发送到reducer,如果我来自reducer的console.log,我可以在控制台中看到它。
我什至把道具挂在开始时间和停止计时器的按钮上,因为我每秒在控制台中看到“ TICK”动作。但是,目前我最大的困惑是,即使我将它挂在了商店上,我似乎也看不到组件中呈现的值。 this.props
在componentDidMount and render(){}
上未定义。但是,同一组件上的按钮不会<button onClick={this.props.startTimer}>Start</button>
触发startTimer操作,因此它正在更新状态,那么为什么组件未反映该状态以及为什么我的this.props值在组件中未定义?噢,是的,即使我正在使用thunk
中间件进行取/应许,我的另外两个redux reducer /动作也可以正常工作。欢迎任何帮助/建议,因为这是我在应用程序上遇到的最后障碍
代码如下:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import thunk from 'redux-thunk';
import reducers from './reducers'
export const store = createStore(reducers, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
减速器
export default (state = [], action) => {
switch (action.type) {
case "FORECAST_WEATHER":
return action.payload;
default: return state;
}
};
export default (state = [], action) => {
switch (action.type) {
case "CURRENT_WEATHER":
return action.payload;
default: return state;
}
};
const START_TIMER = "START_TIMER";
const STOP_IT = "STOP_IT";
const RESUME_IT = "RESUME_IT";
const TICK = "TICK";
const initialState = {
timerOn: true,
timerStart: 0,
timerTime: 30
};
export default (state = initialState, action) => {
console.log("state is ", state);
console.log("action is ", action);
switch (action.type) {
case START_TIMER:
return {
...state,
timerOn: true,
timerTime: state.timerTime,
timerStart: Date.now() - state.timerTime,
timerId: action.timerId
};
case STOP_IT: {
return {
...state,
timerOn: false,
timerStart: 0
};
}
case TICK:
return { ...state, timerTime: state.timerTime + 1 };
default:
return state;
}
};
import { combineReducers } from "redux";
import currentWeatherReducer from './currentWeatherReducer';
import forecastReducer from './forecastReducer';
import currentTimeReducer from './currentTimeReducer';
export default combineReducers({currentWeather: currentWeatherReducer, forecast: forecastReducer, currentTime: currentTimeReducer});
动作
import { getForecast } from "../api/GET/getForecast";
import { getCurrentWeather } from "../api/GET/getCurrentWeather";
export const fetchCurrentWeather = () => async (dispatch, getState) => {
const { name, dt, main } = await getCurrentWeather();
const cityProperties = { name, dt, main };
dispatch({ type: "CURRENT_WEATHER", payload: cityProperties });
};
export const fetchForecasts = () => async (dispatch) => {
const { list } = await getForecast();
dispatch({ type: "FORECAST_WEATHER", payload: list });
};
计时器组件
import React, { useState, useEffect } from "react";
import "./Timer.scss";
import { connect } from "react-redux";
import { start, stop, tick } from "../../actions";
class Timer extends React.Component {
constructor(props) {
super(props);
}
handleStop = () => {
clearInterval(this.props.timerId);
this.props.stopTimer();
};
componentDidMount() {
console.log("TIMER PROPS IS UNDEFINED HERE", this.props);
}
render() {
const { timerTime } = this.props;
console.log("PROPS ARE ALSO UNDEFINED HERE", this.props);
return (
<div className="timer-container">
<button onClick={this.props.startTimer}>Start</button>
TIME IS: {timerTime}
<button onClick={this.handleStop}>Stop</button>
<button onClick={this.props.resetTimer}>Reset</button>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
timerOn: state.timerOn,
timerStart: state.timerStart,
timerTime: state.timerTime,
timerId: state.timerId,
};
};
const mapDispatchToProps = (dispatch) => {
console.log("dispatch", dispatch);
let timerId;
return {
startTimer: () => {
timerId = setInterval(() => dispatch({ type: "TICK" }), 1000);
dispatch({ type: "START_TIMER", timerId });
},
stopTimer: () => {
dispatch({ type: "STOP_IT" });
clearInterval(timerId);
},
resetTimer: () => dispatch({ type: "RESUME_IT" }),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Timer);
连接到商店的其他组件可以正常工作
import React from "react";
import "./Header.scss";
import Timer from "../Timer";
import { connect } from "react-redux";
import { fetchCurrentWeather } from "../../actions";
class Header extends React.Component {
componentDidMount() {
this.props.fetchCurrentWeather();
console.log(this.props.currentWeather);
}
render() {
const { name, dt, temp } = this.props.currentWeather
return (
<div className="top-header">
<div className="current-city info">
<h1>{name}</h1>
<div className="time-container">
<i className="time-icon icon" >xxx</i>
<span className="time-text">{dt}</span>
<i className="time-icon icon" >xxx</i>
</div>
<span className="degrees">{temp}°</span>
</div>
<Timer />
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return { currentWeather: state.currentWeather };
};
export default connect(mapStateToProps, { fetchCurrentWeather })(Header);
连接到商店的另一个有效的组件
import React, { useState, useEffect } from "react";
import "./WeatherCard.scss";
import {fetchForecasts} from '../../actions';
import {connect} from 'react-redux';
class WeatherCard extends React.Component {
constructor(props) {
super(props);
}
componentDidMount(){
this.props.fetchForecasts();
console.log('PROPS IS DEFINED HERE', this.props);
}
render() {
const allRelevantData = Object.entries(this.props.forecast).map(([key, value]) => {
const dateTime = new Date(value.dt * 1000);
const day = dateTime.toString().slice(0, 3);
const item = {
day: day,
temp: Math.round(value.main.temp),
weatherMetaData: value.weather[0],
};
return item;
});
const uniqueForecasts = Array.from(
new Set(allRelevantData.map((a) => a.day))
).map((day) => {
return allRelevantData.find((a) => a.day === day);
});
return uniqueForecasts.map(({ day, temp, weatherMetaData }, index) => {
if (index < 5) {
return (
<div className="weather-card" key={index}>
<div className="day-temperature-container">
<span className="day">{day}</span>
<span className="temperature fade-in">{temp}°</span>
</div>
<div className="weather-description">
<span
className="icon weather"
style={{
background: `url(http://openweathermap.org/img/wn/${weatherMetaData.icon}.png)`,
}}
/>
<p>{weatherMetaData.description}</p>
</div>
</div>
);
}
});
}
}
const mapStateToProps = (state, ownProps) => {
return {forecast: state.forecast};
};
export default connect(mapStateToProps, {fetchForecasts})(WeatherCard);
答案 0 :(得分:1)
您需要从带有化简器的状态树中提取状态。您有三个减速器。 在Timer.js文件中,您需要从 currentTime reducer整形的状态中提取状态。 如果您在 Timer.js 中更改 mapStateToProps ,如下所示;您可以获取状态:
Timer.js
...
//pulling of states from the state tree that shaped with currentTime reducer
const mapStateToProps = (state) => {
return {
timerOn: state.currentTime.timerOn,
timerStart: state.currentTime.timerStart,
timerTime: state.currentTime.timerTime,
timerId: state.currentTime.timerId,
};
};
没有关系,但我只是想推广使用redux-logger :) reducer.js
...
//Create Store
// import { createLogger } from 'redux-logger';
const loggerMiddleware = createLogger();
const rootReducer = combineReducers({
currentWeather: currentWeatherReducer,
forecast: forecastReducer,
currentTime: currentTimeReducer
})
export const store = createStore(
rootReducer,
applyMiddleware(
thunkMiddleware,
loggerMiddleware
)
);
答案 1 :(得分:0)
听起来您在从redux reducer状态中拉出时遇到困难。
通常我会
2。)在我的setInterval函数中,我将分派一个操作,以在间隔的每次迭代期间递增化径器的初始状态值0 ++(currentValue ++)。
3。)在我的组件中,我将把道具传递给组件。请确保检查是否需要映射值或不使用.map函数直接将其传递。
我还建议使用Moment.js。您可以使用该库轻松完成所有这些操作。