我正在尝试使用来自redux的道具作为渲染这样的全态组件的起点:
const MyComp = (props) => {
const initState = {
newAttribs: [...props.attribs]
};
const [state, setState] = useState(initState)
console.log(state)
};
const mapStateToProps = (fromRedux) => {...};
const mapDispatchToProps = (dispatch) => {...};
export default connect(mapStateToProps, mapDispatchToProps)(React.memo(MyComp));
但是如果我console.log(state)
显示newAttribs
的空数组,即使其中有initState newAttribs
。
有人可以阐明如何正确执行此操作吗? 谢谢。
编辑:
发布代码段时出错,我现在对其进行了更新。
const mapStateToProps
和const mapDispatchToProps
显然必须在组件范围之外,而且它们不在。
答案 0 :(得分:1)
您需要注意两件事
sqliteCon.Open();
var filename = string.Concat("Filename", DateTime.Now.ToString("ddMMyyHHmmss"), ".txt");//THIS STRING ALLOW TO BUILD FILES EVERY TIME THE USER CHANGE ITEM AND WANTO TO PRINT IT
string datoR, datoN;
//DONE: Keep SQL readable
string Cmd =
@"SELECT tabStoricoDetail.id
FROM tabStoreExec JOIN
tabStoricoDetail ON tabStoreExec.idSE = tabStoricoDetail.id
WHERE tabStoricoDetail.NomeItem LIKE @prmNome";
//DONE: wrap IDisposable into using
using (SqlCommand Cmd = new SqlCommand(Cmd, sqliteCon))
{
Cmd.Parameters.AddWithValue("@prmNome", this.txtSrcVR.Text);
using (var reader = Cmd.ExecuteReader())
{
//DONE: do not concat strings but use Path.Combine
string file = Path.Combine(@"D:\Reports", filename);
using (TextWriter tw = new StreamWriter(file, true))
{
while (reader.Read())
{
//DONE: Convert.To is a safier (culture independent) approach then .ToString()
string datoI = Convert.ToString(reader[0]);
tw.WriteLine(datoI);
}
}
}
}
和mapStateToProps
应该在组件范围之外定义mapDispatchToProps
发生更改时,您需要更新组件状态,可以使用props.attribs
示例
useEffect
如果在初始挂载之前来自redux存储的数据可用,那么您将在const MyComp = (props) => {
const initState = {
newAttribs: [...props.attribs]
};
const [state, setState] = useState(initState)
useEffect (() => {
setState({ ...state, newAttribs: [...props.attribs] })
}, [props.attribs])
console.log(state)
};
const mapStateToProps = (fromRedux) => {...};
const mapDispatchToProps = (dispatch) => {...};
export default connect(mapStateToProps, mapDispatchToProps)(React.memo(MyComp));
中看到它